到目前为止我的代码:
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)
方法来获得该输出。我该怎么办?
答案 0 :(得分:2)
您可以使用rsplit
并仅执行一次拆分来获得该输出,即:
'Christopher Arthur Hansen Brooks'.rsplit(' ', 1)
返回一个列表:
['Christopher Arthur Hansen', 'Brooks']
您可以解压缩到firstname
和lastname
:
firstname, lastname = 'Christopher Arthur Hansen Brooks'.rsplit(' ', 1)
对于可能很短的输入(即用户只输入名字),如果你还要打开包装,最好使用rpartition
;解包只需要处理返回的3元素元组:
firstname, _, lastname = 'Christopher Arthur Hansen Brooks'.rpartition(' ')