简体   繁体   English

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

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

I have a for loop that prints out each line in the text as a element and appends it to the list.我有一个 for 循环,将文本中的每一行作为一个元素打印出来并将其附加到列表中。 It is putting it with single quotes, however I would like it to placed in the element with a double quote.它用单引号括起来,但是我希望它用双引号放在元素中。 Not sure what to use and where to start.不确定要使用什么以及从哪里开始。

My file contains我的文件包含

google.com 
yahoo.com
facebook.com 

The script I have is我的脚本是

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

The result I would like is我想要的结果是

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

Any help is appreciated任何帮助表示赞赏

You can use json.dumps for this, and use rstrip to remove trailing spaces and linebreaks.您可以为此使用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: Output:

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

As it was mentioned before, Python only prints single quotes, if the type of given element is string, as in your case.如前所述, Python 仅打印单引号,如果给定元素的类型是字符串,如您的情况。 If you need to have explicitly double quotes around your strings, then use f-strings:如果您需要在字符串周围有明确的双引号,请使用 f-strings:

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

It will give you它会给你

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

which is probably what you're looking for.这可能是您正在寻找的。

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

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