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

Tha*_*kay 8 python string list python-3.x

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

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

例如

['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))
Run Code Online (Sandbox Code Playgroud)

我是python的新手,并没有找到任何关于此的内容.有谁知道如何解决这个问题?

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

fal*_*tru 24

你无法改变str工作方式list.

如何使用用于字符串的JSON格式".

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

>>> import json
>>> print(json.dumps(animals))
["dog", "cat", "fish"]
Run Code Online (Sandbox Code Playgroud)
import json

...

textfile.write(json.dumps(words))
Run Code Online (Sandbox Code Playgroud)

  • `json.dumps('dog')` 将 `'"dog"'` 输出到文件,但我想要 `"dog"`。怎么做? (3认同)

Har*_*vey 7

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

str(words).replace("'", '"')
Run Code Online (Sandbox Code Playgroud)

可能还扩展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"
Run Code Online (Sandbox Code Playgroud)