如何使用双引号打印列表中的元素

问题描述 投票:1回答:2

我有一个for循环,可将文本中的每一行作为元素打印出来,并将其附加到列表中。它用单引号引起来,但是我希望将其放在元素中用双引号引起来。不确定使用什么以及从哪里开始。

我的文件包含

google.com 
yahoo.com
facebook.com 

我的脚本是

with open('file') as target:
    addresses=[]
    for i in target:
        addresses.append(i)
print(addresses)

我想要的结果是

["google.com", "yahoo.com", "facebook.com"]

感谢您的任何帮助

python python-3.x string list for-loop
2个回答
4
投票

您可以为此使用json.dumps,并使用rstrip删除尾随空格和换行符。

import json

with open('test.txt') as target:
    addresses=[]
    for i in target:
        addresses.append(i.rstrip())

print(json.dumps(addresses))

输出:

["google.com", "yahoo.com", "facebook.com"]

1
投票

如前所述,如果给定元素的类型为字符串,Python只会打印单引号,就像您所使用的情况一样。如果您需要在字符串周围使用双引号,请使用f字符串:

with open('file') as target:
    addresses=[]
    for i in target:
        addresses.append(f"\"{i.rstrip()}\"")
print(addresses)

它将给你

['"google.com"', '"yahoo.com"', '"facebook.com"']

这可能是您要寻找的。

© www.soinside.com 2019 - 2024. All rights reserved.