McLeodx McLeodx - 4 months ago 20
Python Question

Wrap quotes around many strings in Python

Afghanistan
Albania
Algeria
etc


I have a list of countries, as above, copied from a txt file. I would like to create a list called
countries
containing all of these entries, without having to go down the list one-by-one wrapping each entry in quotes and add commas.

How can this be done in an efficient and quick way?

Final list should look like:

countries = [
"Afghanistan",
"Albanian",
"Algeria"....
]


There are lines with 2+ separate strings,
Puerto Rico
for example. splitlines() seems to separate both words, instead of creating a list entry for each line.

Answer

Quotes and commas are for lists and strings specified as literals in code. You don't need that for data you are reading programmatically.

Just read the lines and strip off the tailing newlines.

with open('countries.text') as src:
    countries = [row.strip('\n') for row in src]
Comments