TourEiffel
TourEiffel

Reputation: 4444

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

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 ?

Upvotes: 0

Views: 157

Answers (5)

Chandler Bong
Chandler Bong

Reputation: 461

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'" 

Upvotes: 0

ILS
ILS

Reputation: 1380

Have you tried repr?

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

Upvotes: 2

MrMattBusby
MrMattBusby

Reputation: 160

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'"

Upvotes: 0

GordonAitchJay
GordonAitchJay

Reputation: 4880

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

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27334

You could do it like this:

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

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

Output:

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

Upvotes: 2

Related Questions