Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to list conversion in python

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?

like image 467
self Avatar asked Mar 28 '12 10:03

self


People also ask

Can we convert string to list in Python?

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.

How do you store a string in a list Python?

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.

How do I convert a string to a list of strings?

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.


2 Answers

Use list comprehensions:

s = '1989, 1990'
[x.strip() for x in s.split(',')]

Short and easy.

Additionally, this has been asked many times!

like image 90
hochl Avatar answered Sep 18 '22 08:09

hochl


Use the split method:

>>> '1989, 1990'.split(', ')
['1989', '1990']

But you might want to:

  1. remove spaces using replace

  2. 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.

like image 22
jpic Avatar answered Sep 18 '22 08:09

jpic