String to list in Python

Question:

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?

Asked By: Nicole

||

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

Answered By: Katriel

Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Answered By: Ojitha

Or for fun:

>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>> 

ast.literal_eval

Answered By: U12-Forward

Maybe like this:

list('abcdefgh') # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Answered By: Aldrich Dienhart

You can use the split() function, which returns a list, to separate them.

letters = 'QH QD JC KD JS'

letters_list = letters.split()

Printing letters_list would now format it like this:

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

Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:

print(letters_list[2])

This would print the third element of your list, which is ‘JC’

Answered By: seb_rc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.