我想用列表中的双引号替换单引号 [英] I want to replace single quotes with double quotes in a list
本文介绍了我想用列表中的双引号替换单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我正在编写一个程序,该程序需要一个文本文件,将其分解为单词,然后将列表写入新的文本文件.
So I am making a program that takes a text file, breaks it into words, then writes the list to a new text file.
我遇到的问题是我需要列表中的字符串使用双引号而不是单引号.
The issue I am having is I need the strings in the list to be with double quotes not single quotes.
例如
当我想要这个["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新手,对此一无所获. 有人知道如何解决这个问题吗?
I am new to python and haven't found anything about this. Anyone know how to solve this?
推荐答案
您不能更改str
对list
的工作方式.
You cannot change how str
works for list
.
关于使用 JSON格式(对于字符串使用"
)的情况.
How about using JSON format which use "
for strings.
>>> 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))
这篇关于我想用列表中的双引号替换单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文