是否可以在单个语句中拆分和分配字符串?

2024-04-28 05:39:19 发布

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

一个字符串可以被拆分,一些单词可以被赋给一个元组吗?

例如:

a = "Jack and Jill went up the hill"
(user1, user2) = a.split().pick(1,3) # picks 1 and 3 element in the list.

这样的单程航班有可能吗?如果是,语法是什么。


Tags: andthe字符串单词split元组jackup
3条回答

切片支持步骤参数

a = "Jack and Jill went up the hill"
(user1 , user2) = a.split()[0:4:2] #picks 1 and 3 element in the list

但是,虽然用Python编写时髦的单行程序是可能的,但它肯定不是进行这种练习的最佳语言。

你可以这样做

a = "Jack and Jill went up the hill"
user1, _, user2, _ = a.split(" ", 3)

其中_表示我们不关心值,并且split(" ", 3)将字符串分成4段。

如果你想变得花哨,你可以使用^{}

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values.

示例:

>>> from operator import itemgetter
>>> pick = itemgetter(0, 2)
>>> pick("Jack and Jill went up the hill".split())
('Jack', 'Jill')

或作为一行(不含进口):

>>> user1, user2 = itemgetter(0, 2)("Jack and Jill went up the hill".split())

相关问题 更多 >