Roald Andre Kvarv
Roald Andre Kvarv

Reputation: 197

How can i rearrange the elements in a string to a wanted result if i add new elements to the string

I am making a function where if i type my name. lets say 'Namey Fakey Dake', that would leave Namey to the first name, and Dake the lastname, and fakey would be the characters middle name. i want to rearrange them, and even if i add more middle names i want those to be automaticly rearranged

As i am not that experienced in python, there are limits to my skills. i have tried to use a single print function manually rearrange them, but that would only work if i only had 1 middle in the way i wrote it, and i dont know how to actually fix it.

def getName(firstName, middleName, lastName):
    print(lastName + ',', firstName, middleName[0] + '.')
getName('Roald', 'Andre Eric', 'Kvarv')

i expect the output: Kvarv, Roald A. E. but when i add more names i get: Kvarv, Roald A.

Upvotes: 2

Views: 88

Answers (1)

Chris
Chris

Reputation: 29742

Use str.join with str.split:

def getName(firstName, middleName, lastName):
    print(lastName + ',', firstName, ' '.join(s[0]+'.' for s in middleName.split()))
getName('Roald', 'Andre Eric', 'Kvarv')

Output:

Kvarv, Roald A. E.

Upvotes: 3

Related Questions