我正试着用python打印一个带有“引号”而不是“引号”的列表。
例如,我要给myList = ['a','b','c','d']什么我想要给myList = ["a","b","c","d"]什么
提前感谢!
发布于 2018-07-21 03:51:34
您可以使用json来完成此操作
import json
myList = ['a','b','c','d']
out = json.dumps(myList)
print(out)
# ["a", "b", "c", "d"]发布于 2018-07-21 03:55:10
要做到这一点,最简单的方法是使用json (因为这恰好是JSON使用的格式):
import json
print(json.dumps(['a', 'b', 'c', 'd'])下面是关于如何在纯python中实现该功能的一些见解:
list类的内置__repr__方法只是在每个元素上调用__repr__ ...在本例中为str。
str.__repr__具有使用单引号的行为。没有(直接的)方法来改变这一点。
你可以使用它自己的__repr__函数来滚动你自己的类型,这样做就足够容易了……
class mystr(str):
def __repr__(self):
return '"' + str.__repr__(self)[1:-1].replace('"', r'\"') + '"'
yourlist = ['a', 'b', 'c', 'd']
# convert your list in place
for i,v in enumerate(yourlist):
yourlist[i] = mystr(v)
print(yourlist)发布于 2018-07-21 05:03:15
您可以创建自己的字符串子类,其表示形式使用"字符:
class MyStr(str):
# Special string subclass to override the default representation
# method. Main purpose is to prefer using double quotes and avoid hex
# representation on chars with an ord() > 128
def __repr__(self):
quotechar = '"'
rep = [quotechar]
for ch in self:
# Control char?
if ord(ch) < ord(' '):
# remove the single quotes around the escaped representation
rep += repr(str(ch)).strip("'")
# Does embedded quote match quotechar being used?
elif ch == quotechar:
rep += "\\"
rep += ch
# Else just use others as they are.
else:
rep += ch
rep += quotechar
return "".join(rep)
myList = ['a','b','c','d']
print(myList) # -> ['a', 'b', 'c', 'd']
print([MyStr(element) for element in myList]) # -> ["a", "b", "c", "d"]https://stackoverflow.com/questions/51449417
复制相似问题