简体   繁体   中英

How to add double quotes on every element of list?

My list is [1,2,3,a,4,g]

I want to print my list in this way ["1","2","3","a","4","g"] .

How to add double quotes on every element in a list?

' '.join('"%s"' % x for x in newst)

I suspect what you're looking for it to convert all elements of the list to strings:

a = 'a'
g = 'g'
myList = [1,2,3,a,4,g]

print(myList)

[1, 2, 3, 'a', 4, 'g']

myList = list(map(str,myList))

['1', '2', '3', 'a', '4', 'g']

Python's list representation uses single quotes though. If you want them to be double quotes, you'll need to convert them yourself:

print(myList.__repr__().replace("'",'"')) 

["1", "2", "3", "a", "4", "g"]

Note that this may cause some inconsistencies if some of the strings contain single quotes themselves. You would then need more sophisticated formatting logic:

print("["+", ".join(map('"{}"'.format,myList))+"]")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM