How to Convert list to string and keep the 'quotes'

Question:

I have the following list :

StringTest = ['A','B','C','D']

The output excepted is :

"'A','B','C','D'" 

but it seems that the ” are perma deleted.

Below is the code I tried :

StringTest = ['A','B','C','D']
StringTest = ','.join(StringTest )
print(StringTest )

which returns :

"A,B,C,D"

How can I do ?

Asked By: TourEiffel

||

Answers:

You can do something weird like this:

StringTest = "'"+"','".join(StringTest)+"'"
Answered By: Marcus

This is expected operation for string functions. If you want the "’" character included in your string, your input string needs to include it like "'A'". There are many ways to do this using string manipulation and iterating thru your input list, e.g.

','.join([f"'{each}'" for each in StringTest])

As noted below in comments, if you want to embed this string within another set of quotes since the __str__ will strip them using print(), you can:

>>> '"{}"'.format(','.join([f"'{each}'" for each in StringTest]))
'"'A','B','C','D'"'
>>> print(_)
"'A','B','C','D'"
Answered By: MrMattBusby

It seems weird but it is an easy solution anyway:

str_edit = '"'+ str(StringTest).replace('[', '').replace(']', '') + '"'
print(str_edit.replace(" ", ''))

output:

"'A','B','C','D'" 
Answered By: Chandler Bong

You could do it like this:

StringTest = ['A','B','C','D']

print('"'+','.join(f"'{s}'" for s in StringTest)+'"')

Output:

"'A','B','C','D'"
Answered By: Cobra

Use str.join to add the commas between each character, and use a generator expression to add the single quotes to each character:

string_test = ['A', 'B', 'C', 'D']
string_test = ",".join(f"'{c}'" for c in string_test)
print(string_test)

Output:

'A','B','C','D'

See also: f-strings

Answered By: GordonAitchJay

Have you tried repr?

print(','.join(map(repr, StringTest)))
# 'A','B','C','D'
print(repr(','.join(map(repr, StringTest)))
# "'A','B','C','D'"
Answered By: ILS

It will also work using simply the str() method on the list directly:

StringTest = ['A','B','C','D']
StringTest = str(StringTest)
StringTest = StringTest.strip("[]")

print(StringTest)

Result:

'A', 'B', 'C', 'D'

We use this in a few production programs, as it’s pretty fast.

Answered By: user56700
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.