使用split将字符串拆分为选择的空格。(“”,int)

时间:2016-11-18 09:54:39

标签: python string python-3.x split

到目前为止我的代码:

firstname = 'Christopher Arthur Hansen Brooks'.split(' ',1) # [0] selects the first element of the list
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)

我想输出:

['Christopher Arthur Hansen', 'Brooks']

我只想使用split(' ', int)方法来获得该输出。我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以使用rsplit并仅执行一次拆分来获得该输出,即:

'Christopher Arthur Hansen Brooks'.rsplit(' ', 1)

返回一个列表:

['Christopher Arthur Hansen', 'Brooks']

您可以解压缩到firstnamelastname

firstname, lastname = 'Christopher Arthur Hansen Brooks'.rsplit(' ', 1)

对于可能很短的输入(即用户只输入名字),如果你还要打开包装,最好使用rpartition;解包只需要处理返回的3元素元组:

firstname, _, lastname = 'Christopher Arthur Hansen Brooks'.rpartition(' ')