I have a string.
s = '1989, 1990'
I want to convert that to list using python & i want output as,
s = ['1989', '1990']
Is there any fastest one liner way for the same?
Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.
Method#1: Using split() method The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
Use list comprehensions:
s = '1989, 1990'
[x.strip() for x in s.split(',')]
Short and easy.
Additionally, this has been asked many times!
Use the split method:
>>> '1989, 1990'.split(', ')
['1989', '1990']
But you might want to:
remove spaces using replace
split by ','
As such:
>>> '1989, 1990,1991'.replace(' ', '').split(',')
['1989', '1990', '1991']
This will work better if your string comes from user input, as the user may forget to hit space after a comma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With