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?
-
2How did you try to split the string?Felix Kling– Felix Kling2011年03月27日 22:56:25 +00:00Commented Mar 27, 2011 at 22:56
-
I recommend you Google a free online book called "Dive Into Python"invert– invert2011年03月28日 09:04:09 +00:00Commented Mar 28, 2011 at 9:04
-
Off-topic, but for search's sake : Convert string representation of list to list.Skippy le Grand Gourou– Skippy le Grand Gourou2019年06月19日 09:24:36 +00:00Commented Jun 19, 2019 at 9:24
5 Answers 5
>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
Return a list of the words in the string, using
sepas the delimiter string. Ifmaxsplitis given, at mostmaxsplitsplits are done (thus, the list will have at mostmaxsplit+1elements). Ifmaxsplitis not specified, then there is no limit on the number of splits (all possible splits are made).If
sepis given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',')returns['1', '', '2']). Thesepargument 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
sepis not specified or isNone, 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 aNoneseparator returns[].For example,
' 1 2 3 '.split()returns['1', '2', '3'], and' 1 2 3 '.split(None, 1)returns['1', '2 3 '].
Comments
Here the simples
a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
1 Comment
[*'abcdefgh']Maybe like this:
list('abcdefgh') # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
2 Comments
Or for fun:
>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>>
ast.literal_eval
Comments
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'