McLeodx McLeodx - 5 months ago 31
Python Question

Wrap quotes around many strings in Python


I have a list of countries, as above, copied from a txt file. I would like to create a list called
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 = [

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.


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]