How do you convert a string into a list?
Say the string is like text = \"a,b,c\"
. After the conversion, text == [\'a\', \'b\', \'c\']
and h
I usually use:
l = [ word.strip() for word in text.split(',') ]
the strip
remove spaces around words.
split()
is your friend here. I will cover a few aspects of split()
that are not covered by other answers.
split()
, it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.Example:
>>> " \t\t\none two three\t\t\tfour\nfive\n\n".split()
['one', 'two', 'three', 'four', 'five']
split()
behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.Example:
>>> ",,one,two,three,,\n four\tfive".split(',')
['', '', 'one', 'two', 'three', '', '\n four\tfive']
So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:
words = [item.strip() for item in string.split(',')]
Example:
>>> "one,two,three,,four".split(',,')
['one,two,three', 'four']
To coalesce multiple delimiters into one, you would need to use re.split(regex, string)
approach. See the related posts below.
Example 1
>>> email= "myemailid@gmail.com"
>>> email.split()
#OUTPUT
["myemailid@gmail.com"]
Example 2
>>> email= "myemailid@gmail.com, someonsemailid@gmail.com"
>>> email.split(',')
#OUTPUT
["myemailid@gmail.com", "someonsemailid@gmail.com"]
In case you want to split by spaces, you can just use .split()
:
a = 'mary had a little lamb'
z = a.split()
print z
Output:
['mary', 'had', 'a', 'little', 'lamb']
All answers are good, there is another way of doing, which is list comprehension, see the solution below.
u = "UUUDDD"
lst = [x for x in u]
for comma separated list do the following
u = "U,U,U,D,D,D"
lst = [x for x in u.split(',')]
To convert a string
having the form a="[[1, 3], [2, -6]]"
I wrote yet not optimized code:
matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
matrixAr.append(row)
print matrixAr