String to List in Python

String to list in Python

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']

split:

Return a list of the words in the
string, using sep as the delimiter
string. If maxsplit is given, at most
maxsplit splits are done (thus, the
list will have at most maxsplit+1
elements). If maxsplit is not
specified, then there is no limit on
the number of splits (all possible
splits are made).

If sep is given, consecutive
delimiters are not grouped together
and are deemed to delimit empty
strings (for example,
'1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of
multiple characters (for example,
'1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string
with a specified separator returns
[''].

If sep is not specified or is None, a
different splitting algorithm is
applied: runs of consecutive
whitespace are regarded as a single
separator, and the result will contain
no empty strings at the start or end
if the string has leading or trailing
whitespace. Consequently, splitting an
empty string or a string consisting of
just whitespace with a None separator
returns [].

For example, ' 1 2 3 '.split()
returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

How to check if a string is a substring of items in a list of strings

To check for the presence of 'abc' in any string in the list:

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
...

To get all the items containing 'abc':

matching = [s for s in xs if "abc" in s]

How to convert a string into list with one element in python

Simply use [..]:

a = 'abc'
b = [a]
print(b)

[..] is list notation, you can feed it a comma-separated list of values. For instance [1,4,2,5,'a',1+2,4/3,3.1415],... Or as specified in the documentation:

(..) The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

Converting a String to a List of Words?

Try this:

import re

mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ", mystr).split()

How it works:

From the docs :

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.

so in our case :

pattern is any non-alphanumeric character.

[\w] means any alphanumeric character and is equal to the character set
[a-zA-Z0-9_]

a to z, A to Z , 0 to 9 and underscore.

so we match any non-alphanumeric character and replace it with a space .

and then we split() it which splits string by space and converts it to a list

so 'hello-world'

becomes 'hello world'

with re.sub

and then ['hello' , 'world']

after split()

let me know if any doubts come up.

Convert string list to list in python

You can do it in one line using literal_eval:

from ast import literal_eval

val = ['54','147','187','252','336']
a = [i.split('/')[-1] for i in literal_eval(val)]

print(a)

Output:

['54', '147', '187', '252', '336']

literal_eval() converts your string into a list, and then i.split('/')[-1] grabs what's after the slash.

How to make the whole string a list element?

Just use braces directly:

[str1]

Or if you want to stick with list:

list((str1,))

does the same.

How to convert comma-delimited string to list in Python?

You can use the str.split method.

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

If you want to convert it to a tuple, just

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

If you are looking to append to a list, try this:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']


Related Topics



Leave a reply



Submit