user8314628
user8314628

Reputation: 2042

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?

Upvotes: 2

Views: 78

Answers (3)

Wups
Wups

Reputation: 2569

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))

Upvotes: 2

Mad Physicist
Mad Physicist

Reputation: 114440

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))})'

Upvotes: 1

Barmar
Barmar

Reputation: 781721

You need to use different code to format the date than the numbers, so you can add quotes around it.

values_str = f"({', '.join(values[:-1])}, '{values[-1]}')"

Upvotes: 1

Related Questions