Home > OS >  How do i add a "." between the letters of the initials?
How do i add a "." between the letters of the initials?

Time:12-31

Create a function called initials that takes in a persons names and then returns the initials. You should pass the names using **args.

For example for James Marshall Hendrix it should return J.M.H.

Or, for John Ronald Reuel Tolkien it should return J.R.R.T (one *arg to rule them all).

My outputs are JMH AND JRRT But i need to output them as the ones above.

def initials(*args):
    result = "" 
    for word in args:
        result  = word[0].upper()
    return result

if __name__ == "__main__":
  print(initials("James", "Marshall", "Hendrix")) # should print the return value of "J.M.H"
  print(initials("John", "Ronald", "Reuel", "Tolkien")) # should print the return value of "J.R.R.T"

CodePudding user response:

def initials(*args):
    result = []
    for word in args:
        result.append(word[0])
    return ".".join(result)


if __name__ == "__main__":
    print(initials("James", "Marshall", "Hendrix"))  # should print the return value of "J.M.H"
    print(initials("John", "Ronald", "Reuel", "Tolkien"))  # should print the return value of "J.R.R.T"

Here is the fixed code, we store the result in a list instead of a string like how you did before, and we join the list with . at the end.

CodePudding user response:

You can compact all that with a list comprehension:

def initials(*args):
    return '.'.join([n[0] for n in args])

print(initials("James", "Marshall", "Hendrix")) 
# J.M.H
print(initials("John", "Ronald", "Reuel", "Tolkien"))
# J.R.R.T

Edit: (thanks to azro): you can simplify it even further using a generator; it will be slower though (read ShadowRanger's very interesting comment below):

    return '.'.join(n[0] for n in args)

CodePudding user response:

Hi you can just add a "." when you take the first letter and then you can just return it without the first character anyway this method can implement in any other programming language.

def initials(*args):
    result = "" 
    for word in args:
            result  ="."  word[0].upper()
    return result[1:]

if __name__ == "__main__":
  print(initials("James", "Marshall", "Hendrix")) 
  print(initials("John", "Ronald", "Reuel", "Tolkien")) 


    
  • Related