Home > Software engineering >  Add quotes to every single entry of a list
Add quotes to every single entry of a list

Time:12-22

I have a list that goes like

Foo 6
Bar 9
Ding 8
Dong 7
...

I used some online tool to add commas to each entry, but if I try to create a list in python, i get a syntax error

list=[Foo 6, Bar 9, Ding 8, Dong 7,...]

I assume this is because i have strings and integers mixed, so adding quotes does work

list=["Foo 6, Bar 9, Ding 8, Dong 7,..."]

But this has only one entry, so its useless. Is there any way to convert this into

list=["Foo 6", "Bar 9", "Ding 8", "Dong 7",...]

Thanks for the help

CodePudding user response:

I always use below when i need to create a list from a table copied values

string = """Foo 6
Bar 9
Ding 8
Dong 7"""

for i in string.split("\n"):
    print(f"\"{i.strip()}\"", end=",")

Now the output is

"Foo 6","Bar 9","Ding 8","Dong 7",

Just Copy and paste to variable

After reading comment if you want a list variable you can run below

string = '''Foo 6
Bar 9
Ding 8
Dong 7'''

lis = []
for i in string.split("\n"):
    lis.append(i.strip())

print(lis)

CodePudding user response:

You manage this input by separating the element with "," using split().

l = ["Foo 6, Bar 9, Ding 8, Dong 7"]

new_list = [ele.strip() for ele in l[0].split(",")]

Output:

['Foo 6', 'Bar 9', 'Ding 8', 'Dong 7']
  • Related