首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python shell中使用“quotations而不是‘

在Python shell中使用“quotations而不是‘
EN

Stack Overflow用户
提问于 2018-07-21 03:45:53
回答 4查看 55关注 0票数 0

我正试着用python打印一个带有“引号”而不是“引号”的列表。

例如,我要给myList = ['a','b','c','d']什么我想要给myList = ["a","b","c","d"]什么

提前感谢!

EN

回答 4

Stack Overflow用户

发布于 2018-07-21 03:51:34

您可以使用json来完成此操作

代码语言:javascript
复制
import json

myList = ['a','b','c','d']

out = json.dumps(myList)
print(out)
# ["a", "b", "c", "d"]
票数 3
EN

Stack Overflow用户

发布于 2018-07-21 03:55:10

要做到这一点,最简单的方法是使用json (因为这恰好是JSON使用的格式):

代码语言:javascript
复制
import json
print(json.dumps(['a', 'b', 'c', 'd'])

下面是关于如何在纯python中实现该功能的一些见解:

list类的内置__repr__方法只是在每个元素上调用__repr__ ...在本例中为str

str.__repr__具有使用单引号的行为。没有(直接的)方法来改变这一点。

你可以使用它自己的__repr__函数来滚动你自己的类型,这样做就足够容易了……

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2018-07-21 05:03:15

您可以创建自己的字符串子类,其表示形式使用"字符:

代码语言:javascript
复制
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"]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51449417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档