I have a task to rearrange a sentence with the first name middle initial and last name to last first middle. I don't know how to do this without a stated search or how to make a index. Ive tried it with finding a space between but I don't know how I would rearrange doing this. This is what I have but it doesn't work. If I could get help defining each part I think I could do the rest on my own.
name = input("Enter a name like 'First I. Last: ")
index = name.find(" ")
rearranged = name[3:index]
CodePudding user response:
If you're on Python 3.8 , you should be able to use it like this:
name = 'John C. Smith'
rearranged_name = ' '.join([(word := name.split(' '))[2], *word[:2]])
print(rearranged_name)
Note that in the above, you could also write out *word[:2]
like word[0], word[1]
if you prefer to be more explicit.
Output:
Smith John C.
If you're using an earlier version than 3.8, the following alternative should still work for your use case (adapted from a comment by @TheLazyScripter).
*rest, last = name.split(' ')
rearranged_name = ' '.join([last, *rest])
Where *rest
can also be reworded as two separate variables - first, mi
.
CodePudding user response:
If you expect an exact number of fields, you could assign them directly to names
first, middle_i, last = input("Enter a name like 'First I. Last': ").split()
However, you'll probably find it better/easier to use a regular expression to let the fields be optional or write some other custom parser
import re
name = input("Enter a name like 'First I. Last': ")
match = re.match(r"(?P<first>\w ) (?:(?P<middle>\w\.) )?(?P<last>\w )", name)
if not match:
raise ValueError(f"name is invalid: {name}")
# match.groupdict() is a dict with the members named in it now
>>> name = input("Enter a name like 'First I. Last': ")
Enter a name like 'First I. Last': a b. c
>>> name
'a b. c'
>>> match = re.match(r"(?P<first>\w ) (?:(?P<middle>\w\.) )?(?P<last>\w )", name)
>>> match.groupdict()
{'first': 'a', 'middle': 'b.', 'last': 'c'}
...
>>> name = "foo bar"
...
>>> match.groupdict()
{'first': 'foo', 'middle': None, 'last': 'bar'}