要在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']
split
:
返回列表中的单词 字符串,使用
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
,则a
不同的分割算法是
已应用:连续运行
空格被视为单个
分隔符,结果将包含
开始或结尾没有空字符串
如果字符串开头或结尾
空格.因此,将
空字符串或包含以下内容的字符串
仅带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屋!