我正在尝试在python中用“”而不是“”来打印列表。
例如我得到的myList = ['a','b','c','d']
我想得到的myList = ["a","b","c","d"]
谢谢!
答案 0 :(得分:3)
您可以使用json:
import json
myList = ['a','b','c','d']
out = json.dumps(myList)
print(out)
# ["a", "b", "c", "d"]
答案 1 :(得分:1)
最简单的方法是使用json
(因为这恰好是JSON使用的格式):
import json
print(json.dumps(['a', 'b', 'c', 'd'])
以下是一些有关如何使用纯python做到的见解:
__repr__
类的内置list
方法仅在每个元素上调用__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)
答案 2 :(得分:1)
您可以创建自己的字符串子类,该子类的表示使用// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
// Get the unique ID generated by push() by accessing its key
var postID = newPostRef.key;
个字符:
"
答案 3 :(得分:0)
最简单的方法显然是使用json解决问题:
import json
print('myList = ', json.dumps(myList))
但是无需使用任何其他库即可解决此问题的另一种方法是
myList = ['a','b','c','d']
print('myList = ', end='[')
for i in range(len(myList)):
if i != 0:
print(', \"' + myList[i], end='\"')
else:
print('\"' + myList[i], end='\"')
print(']')