Swapping first and last name positions

淺唱寂寞╮ 提交于 2021-02-18 19:12:48

问题


I need some help in writing the body for this function that swaps the positions of the last name and first name.

Essentially, I have to write a body to swap the first name from a string to the last name's positions.

The initial order is first name followed by last name (separated by a comma). Example: 'Albus Percival Wulfric Brian, Dumbledore'

The result I want is: 'Dumbledore, Albus Percival Wulfric Brian'

But I've tried the following and I'm still not getting the right answer:

temp = name_list[len(name_list)-1]
name_list[len(name_list)-1] = name_list[0] 
name_list[0] = temp

The result is a list, which is not what I want. I'm a new user to Python, so please don't go into too complex ways of solving this.


回答1:


You can do this by splitting the string by the comma—which yields a list—then reversing that list, and joining the list by a comma again to get back a string:

>>> name = 'Albus Percival Wulfric Brian, Dumbledore'
>>> ', '.join(reversed(name.split(', ')))
'Dumbledore, Albus Percival Wulfric Brian'

If you can’t use the reversed function (for whatever reason), then you can do the reversal manually by storing the list elements individually first.

>>> name.split(', ')
['Albus Percival Wulfric Brian', 'Dumbledore']
>>> first, last = name.split(', ')
>>> first
'Albus Percival Wulfric Brian'
>>> last
'Dumbledore'
>>> [last, first]
['Dumbledore', 'Albus Percival Wulfric Brian']
>>> ', '.join([last, first])
'Dumbledore, Albus Percival Wulfric Brian'
>>> last + ', ' + first
'Dumbledore, Albus Percival Wulfric Brian'

As it’s theoretically possible that the string contains multiple commas, you should consider passing 1 as the second parameter to str.split to make sure that you only perform a single split, producing two list items:

>>> 'some, name, with, way, too, many, commas'.split(', ', 1)
['some', 'name, with, way, too, many, commas']

Instead of using str.split, you can also locate the comma in the string and split up the string yourself. You can use str.find to get the index of the comma, and then use sequence splicing to split up the string:

>>> name.index(',')
28
>>> name[:28] # string up to index 28
'Albus Percival Wulfric Brian'
>>> name[30:] # string starting at index 30 (we have to consider the space too)
'Dumbledore'
>>> index = name.index(',')
>>> name[index + 2:] + ', ' + name[:index]
'Dumbledore, Albus Percival Wulfric Brian'



回答2:


You don't need many built in functions for this

return name[name.find(',')+2:]+", "+name[:name.find(',')] 


来源:https://stackoverflow.com/questions/22572902/swapping-first-and-last-name-positions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!