问题
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