到目前为止我的代码如下:
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)方法的输出。我该怎么做呢?
发布于 2016-11-18 17:57:17
您可以通过使用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(' ')https://stackoverflow.com/questions/40674010
复制相似问题