Home > OS >  Print string with ' in python
Print string with ' in python

Time:11-23

I have an array of strings a that I would like to print like e.g.

'a1','a2','a3'

where a1 = a[0], a2 = a[1], a3 = a[2].

For some reason

printformat = ''
for i in range(3):
    printformat =a[i] "',"

prints instead

"a1',a2',a3',"

CodePudding user response:

a = ['a1', 'a2', 'a3']

print(','.join(f"'{i}'" for i in a))

Output:

'a1','a2','a3'

CodePudding user response:

With loop:

printformat = "'"
for i in range(3):
    printformat  = a[i]   "',"
printformat = printformat[:-1]  # Remove trailing comma
print(printformat)

You were exactly adding together three elements, each followed by a quote and a comma. The outer (double) quotes come from interpreter, probably, if you're doing it in REPL.

With more convenient methods:

printformat = ','.join(f"'{x}'" for x in a)
print(printformat)
  • Related