I have a for loop that prints out each line in the text as a element and appends it to the list. 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.
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"]
As it was mentioned before, Python only prints single quotes, if the type of given element is string, as in your case. If you need to have explicitly double quotes around your strings, then use 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.