要在 Python 中列出的字符串 [英] String to list in Python
问题描述
我正在尝试拆分字符串:
I'm trying to split a string:
'QH QD JC KD JS'
进入一个列表,如:
['QH', 'QD', 'JC', 'KD', 'JS']
我该怎么做?
推荐答案
>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
返回单词列表字符串,使用 sep
作为分隔符细绳.如果给定 maxsplit
,最多maxsplit
拆分完成(因此,列表最多有 maxsplit+1
元素).如果 maxsplit
不是指定,则没有限制拆分的数量(所有可能的进行拆分).
Return a list of the words in the string, using
sep
as the delimiter string. Ifmaxsplit
is given, at mostmaxsplit
splits are done (thus, the list will have at mostmaxsplit+1
elements). Ifmaxsplit
is not specified, then there is no limit on the number of splits (all possible splits are made).
如果给定了 sep
,则连续分隔符没有组合在一起并被视为划定空字符串(例如,'1,,2'.split(',')
返回 ['1', '', '2']
).sep
参数可能包括多个字符(例如,'1<>2<>3'.split('<>')
返回 ['1', '2', '3']
).拆分空字符串使用指定的分隔符返回['']
.
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
['']
.
如果 sep
没有被指定或者是 None
,一个不同的分裂算法是应用:连续运行空白被视为单个分隔符,结果将包含开头或结尾没有空字符串如果字符串有前导或尾随空白.因此,分裂一个空字符串或由以下内容组成的字符串只是带有 None
分隔符的空格返回 []
.
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 []
.
例如,' 1 2 3 '.split()
返回 ['1', '2', '3']
和 ' 1 2 3 '.split(None, 1)
返回 ['1', '2 3 ']
.
For example, ' 1 2 3 '.split()
returns ['1', '2', '3']
, and ' 1 2 3 '.split(None, 1)
returns ['1', '2 3 ']
.
这篇关于要在 Python 中列出的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!