Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to add quotes to each item inside a Python list?

Hi everyone!

I am currently learning about Python list but I have a little problem. I know I can create a list and manually add quotes around each item inside my list. For example

fruits = ["Apple", "Oranges", "Watermelon"]

but what if I copied a long list of text and placed it inside a list like this.. Would I have to manually add quotes around each item or is there an easier way to select everything inside this list and add quotes at the same time? I am using VS Code btw to practice my learning if that matters at all. Any help would be much appreciated. Thanks!

sw_planets = [
    Naboo
    Coruscant
    Tatooine
    Coruscant
    Naboo
    Kamino
    Tatooine
    Geonosis
    Christophsis
    Teth
    Tatooine
    Coruscant
    Coruscant
    Utapau
    Kashyyyk
    Mygeeto
    Felucia
    Cato Neimoidia
    Seleucami
    Mustafar
    Polis Massa
    Naboo
    Alderaan
    Tatooine
    Rogue One = 8
    Lah'Mu
    Wobani
    Coruscant
    Jedha
    Yavin IV
    Eadu
    Mustafar
    Scarif
    Corellia
    Mimban
    Vandor-1
    Kessel
    Savareen
    Tatooine
    Alderaan
    Yavin IV
    Hoth
    Dagobah
    Bespin
    Tatooine
    Dagobah
    Endor
    Bespin
    Naboo
    Coruscant
    Jakku
    Takodana
    Starkiller Base
    Hosnian Prime
    D’Qar
    Ahch-To
    D'Qar
    Ahch-To
    Canto Bight
    Crait
    Nevarro
    Arvala-7
    Sorgan
    Tatooine
]

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

As shown in this StackOverflow answer, you can use newline characters in the search and replace. Where \n represents the newline character

# replace
‘\n    ’
# with 
‘”\n    “‘

Or with explicit new lines:

# replace
# with 
‘”
    “‘

Or using python to translate a string:

Import re

quoted_planets = re.findall(r'[\w]+', planets)

You could try

planets_as_string ="""

    Naboo
    Coruscant
    Tatooine
    ...

"""

sw_planets = planets_as_string.split("\n")

This would convert each line in planets_as_string, including empty lines, to a string in the list sw_planets. To get rid of the empty lines while keeping the other strings,

sw_planets = [p for p in planets_as_str.split("\n") if len(p) > 0].