简体   繁体   中英

How can I convert a plain text list to a python 3 list

I would like to take a list of names and put them into a python list with the correct syntax. How could I do this? Because otherwise I would have to go through and put in quotes and commas everywhere and I am dealing with long lists.

For example if I had:

list = [
name
name1
name2
name3
name4
name5
]

How could I change those names to strings without doing each one individually?

You can use.split() and split on the newline characters ( \n ). split() will return an array of names:

>>> x = """name
... name1
... name2
... name3
... name4
... name5
... """

>>> names = x.split('\n')
>>> print(names)
['name', 'name1', 'name2', 'name3', 'name4', 'name5', '']

1- read the plain text from a file then split by \n

2- use this website: https://delim.co/# in the converter settings you could add quotes

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM