How to print a string which is a name with two words in reverse order without commas and unnecessary spaces?

Viewed 107

I have to write a function that takes a string of full names and prints it in reverse order. It also removes unnecessary spaces and commas. Some of the expected output is as follow:

 - >>> reverse_name("Techie, Teddy")
   'Teddy Techie'
   >>> reverse_name("Scumble,    Arnold") 
   'Arnold Scumble'
   >>> reverse_name("Fortunato,Frank")
    'Frank Fortunato'
   >>> reverse_name("von Grünbaumberger, Herbert")
    'Herbert von Grünbaumberger'
   >>> reverse_name("   Duck,     Donald  ") 
    'Donald Duck'
   >>> reverse_name("X,")
     'X'
   >>> reverse_name(",X")
      'X'
   >>> reverse_name(" , Y ")
     'Y'.

I wrote the following code.

def main():
    name=input()
    reverse_name(name)
    print(reverse_name(name))

def reverse_name(string1):
    i = 0
    for index in string1:
        if index != ",":
            i += 1
        else:
            last = string1[i + 1:]
            first = string1[0:i]
            result = last + " " + first
            return result
 if __name__ == "__main__":
      main()

p.s: I must implement a function that takes a string as a parameter and returns a string. The input will also contain a comma which the output will not print.

4 Answers

You could combine split and join after having inverted the output of split:

def reverse_name(s):
    return ' '.join([e.strip() for e in s.split(', ')][::-1])

>>> reverse_name('Techie, Teddy')
'Teddy Techie'

>>> reverse_name('   Duck,     Donald  ')
'Donald Duck'

Here is another option using the re module:

def reverse_name(s):
    return re.sub(r'\s*(.+),\s*(.*\S)\s*', r'\2 \1', s)

Use split() to separate the input at the commas. Strip spaces from each element to remove the extraneous spaces, and then reverse the list.

def reverse_names(string1):
    names = string1.split(',') # split at commas
    names = [name.strip() for name in names] # remove extra spaces
    return " ".join(names[::-1]) # return reversed names as a string

if a comma is guaranty to always be there simply using string1.split(",") will give you a list of the separate words in the string, and simple filter the empty one and removing the trailing white spaces with .strip will do the trick

>>> def reverse_name(text):
        return " ".join( w for w in map(str.strip,reversed(text.split(","))) if w)
#                                        ^removing trailing white space      ^filter empty ones
>>> reverse_name("Techie, Teddy")
'Teddy Techie'
>>> reverse_name("Scumble,    Arnold")
'Arnold Scumble'
>>> reverse_name("von Grünbaumberger, Herbert")
'Herbert von Grünbaumberger'
>>> reverse_name("Fortunato,Frank")
'Frank Fortunato'
>>> reverse_name("X,")
'X'
>>> reverse_name(",X")
'X'
>>> reverse_name(" , Y ")
'Y'
>>> reverse_name("   Duck,     Donald  ")
'Donald Duck'
>>> 

you can use a regular expression to replace all the intermediate non-letter characters with a single space (then remove leading/trailing spaces). Then use a regular rsplit() to separate the first and last name (assuming that only the last name can be composite). Reassemble the inverted split result using join():

import re

def reverse_name(name):
    name = re.sub('\W+',' ',name).strip()
    return " ".join(name.rsplit(' ',1)[::-1])-1])

print(reverse_name("Techie, Teddy"))
print(reverse_name("Scumble,    Arnold"))
print(reverse_name("von Grünbaumberger, Herbert"))
print(reverse_name("Fortunato,Frank"))
print(reverse_name("X,"))
print(reverse_name(",X"))
print(reverse_name(" , Y "))
print(reverse_name("   Duck,     Donald  "))

Teddy Techie
Arnold Scumble
Herbert von Grünbaumberger
Frank Fortunato
X
X
Y
Donald Duck

Of course, this leaves the problem of composite first names such as John-Paul Smith which creates an ambiguity on which words are part of the first and last name. If there is always going to be a comma, then the solution would be different (but you would have to state that explicitly in your question)

Solution based on systematic presence of a comma between last and first name:

def reverse_name(name):    
    names = re.sub('[^,\w]+',' ',name).split(',',1)
    return " ".join(map(str.strip,names)).strip()
Related