Darren Macis Darren Macis - 21 days ago 5
Python Question

Building upon existing function

I was just playing around with functions in order to further my understanding of them and I was curious, is it at all possible to return the users first name and last initial using the following function without adding any additional functions?

name = raw_input("Please enter your full name: ")

def username(a):
print(a[0:6]+a[-1])
username(name)

Answer

If the length of input names can vary and number of names then you will have to use another function split and index. If the user can just enter a single name you will need to add an if or try...except.

a[:a.index(' ')]) will get the first name, from the beginning of the input to the first space

index returns ValueError if the character isn't found so if they might enter just first name surround with try...except

a.split()[-1][0] will get the first letter of the last name even if they enter more than two names (Billy Bob Joe -> Billy J)

name = raw_input("Please enter your full name: ")

def username(a):
    print(a[:a.index(' ')]+' '+a.split()[-1][0])
username(name)