我想用列表中的双引号替换单引号

新手上路,请多包涵

所以我正在制作一个程序,它接受一个文本文件,将其分解成单词,然后将列表写入一个新的文本文件。

我遇到的问题是我需要列表中的字符串使用双引号而不是单引号。

例如

我得到这个 ['dog','cat','fish'] 当我想要这个 ["dog","cat","fish"]

这是我的代码

with open('input.txt') as f:
    file = f.readlines()
nonewline = []
for x in file:
    nonewline.append(x[:-1])
words = []
for x in nonewline:
    words = words + x.split()
textfile = open('output.txt','w')
textfile.write(str(words))

我是 python 的新手,还没有发现任何相关信息。任何人都知道如何解决这个问题?

[编辑:我忘了提到我在 arduino 项目中使用输出,该项目要求列表有双引号。]

原文由 ThatsOkay 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

您无法更改 strlist 的工作方式。

如何使用使用 "JSON 格式 作为字符串。

 >>> animals = ['dog','cat','fish']
>>> print(str(animals))
['dog', 'cat', 'fish']

>>> import json
>>> print(json.dumps(animals))
["dog", "cat", "fish"]


 import json

...

textfile.write(json.dumps(words))

原文由 falsetru 发布,翻译遵循 CC BY-SA 3.0 许可协议

您很可能只想通过替换单引号来替换输出中的双引号:

 str(words).replace("'", '"')

您还 可以 扩展 Python 的 str 类型并用新类型包装字符串,更改 __repr__() 方法以使用双引号而不是单引号。不过,上面的代码最好更简单、更明确。

 class str2(str):
    def __repr__(self):
        # Allow str.__repr__() to do the hard work, then
        # remove the outer two characters, single quotes,
        # and replace them with double quotes.
        return ''.join(('"', super().__repr__()[1:-1], '"'))

>>> "apple"
'apple'
>>> class str2(str):
...     def __repr__(self):
...         return ''.join(('"', super().__repr__()[1:-1], '"'))
...
>>> str2("apple")
"apple"
>>> str2('apple')
"apple"

原文由 Harvey 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题