繁体   English   中英

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

[英]How to print elements in list with double quotes

我有一个 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"]

任何帮助表示赞赏

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

import json

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

print(json.dumps(addresses))

Output:

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

如前所述, Python 仅打印单引号,如果给定元素的类型是字符串,如您的情况。 如果您需要在字符串周围有明确的双引号,请使用 f-strings:

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

它会给你

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

这可能是您正在寻找的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM