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

Python 如何使用双引号打印列表中的元素,python,python-3.x,string,list,for-loop,Python,Python 3.x,String,List,For Loop,我有一个for循环,它将文本中的每一行作为元素打印出来,并将其附加到列表中。它是用单引号引起来的,但是我希望它用双引号放在元素中。不确定使用什么以及从哪里开始 我的文件包含 google.com yahoo.com facebook.com 我的剧本是 with open('file') as target: addresses=[] for i in target: addresses.append(i) print(addresses) 我想要的结果是

我有一个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"]
非常感谢您提供的任何帮助

您可以使用它来删除尾随空格和换行符

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"]
可以使用,也可以使用删除尾随空格和换行符

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"]

正如前面提到的,如果给定元素的类型是string,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"']

这可能就是您要查找的内容。

如前所述,如果给定元素的类型是字符串,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"']

这可能就是你想要的。

为什么你需要引号,特别是双引号?您正在尝试生成JSON数组吗?那就是json.dumps[i.strip for i in target]。请记住,列表['google.com'、'yahoo.com'、'facebook.com']只显示有引号;它不包含任何与字符串“[google.com,yahoo.com,facebook.com]”不同的内容。引号不是字符串的一部分-Python仅在您希望立即打印列表时才添加它。若你们需要不同的引号,那个么手动将列表转换为字符串并添加引号。为什么你们需要引号,特别是双引号?您正在尝试生成JSON数组吗?那就是json.dumps[i.strip for i in target]。请记住,列表['google.com'、'yahoo.com'、'facebook.com']只显示有引号;它不包含任何与字符串“[google.com,yahoo.com,facebook.com]”不同的内容。引号不是字符串的一部分-Python仅在您希望立即打印列表时才添加它。若你们想要不同的报价,那个么手动将列表转换为字符串并添加报价。这非常有效,感谢你们提供了一个解决方案。非常感谢!这非常有效,感谢您提供的解决方案。非常感谢!