'Python how to add quote to one of the element in a list?
values is a list looks like ['13020638659', '711799502', '4681912759', '07/21/2021']
I'd like to connect all of its elements to create a value_str look like this
(13020638659, 711799502, 4681912759, '07/21/2021')
This is what I do values_str = "(%s)" % (', '.join( values ))
But the output would be (13020638659, 711799502, 4681912759, 07/21/2021)
There are no quotes for the datatime string. How can I add quotes on it?
Solution 1:[1]
You can check if the value consists of something else than digits with str.isdigit():
"({})".format(", ".join(v if v.isdigit() else f"'{v}'" for v in values))
Solution 2:[2]
You can attempt to convert strings to integer:
def get_repr(x):
try:
return repr(int(x))
except ValueError:
return repr(x)
f'({",".join(map(get_repr, values))})'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mad Physicist |
