簡體   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