Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to list in Python

I'm trying to split a string:

'QH QD JC KD JS' 

into a list like:

['QH', 'QD', 'JC', 'KD', 'JS'] 

How would I go about doing this?

like image 965
Nicole Avatar asked Mar 27 '11 22:03

Nicole


People also ask

How do I convert a string to a list in Python?

To convert string to list in Python, use the string split() method. The split() is a built-in Python method that splits the strings and stores them in the list.

How do you send a string to a list?

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.


1 Answers

>>> '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 '].

like image 171
Katriel Avatar answered Oct 13 '22 12:10

Katriel