把绳子分成两部分

2024-04-27 18:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子

s = 'abcd qwrre qwedsasd zxcwsacds'

我只想在第一次出现空白时将任何字符串分成两部分。i、 ea='abcd'b='qwrre qwedsasd zxcwsacds'

如果我使用a, b=split(' '),它会给我一个错误,因为要解包的值太多。


Tags: 字符串错误空白splitabcd绳子qwrrezxcwsacds
3条回答

您可以使用标准字符串方法partition,该方法搜索给定的分隔符并返回一个3元组,由前面的字符串部分、分隔符本身和后面的部分组成。

>>> s = 'abcd qwrre qwedsasd zxcwsacds'
>>> s.partition(' ')
('abcd', ' ', 'qwrre qwedsasd zxcwsacds')

你可以用a,b = split(' ', 1)

第二个参数1是要执行的最大拆分数。

s = 'abcd efgh hijk'
a,b = s.split(' ', 1)
print(a) #abcd
print(b) #efgh hijk

有关字符串分割函数的详细信息,请参见^{} in the manual

Python docs

str.split(sep=None, maxsplit=-1)

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 or -1, then there is no limit on the number of splits (all possible splits are made).

'1 2 3'.split(maxsplit=1)
# ['1', '2 3']

相关问题 更多 >