I am attending a beginner course and I am very new to programming. I need to know of a function which generates a username using the first letter of someone's name, the first three letters of a person's surname and a 3 digit number without spaces. So far I have this:
full_name = input("Please enter your name: ")
first_letter = full_name[0]
space_index = full_name.find(" ")
three_letters_surname = full_name[space_index + 1:space_index + 4]
number = random.randrange (1,999)
username = (first_letter, three_letters_surname, number)
print = (username)
The output I get is from using a name like John Wayne is:
"J", "Way", 14
What I want to know is how to change my code so I get something like:
jway014
You might be better off using split()
to break the user's name into parts and then extracting from there. This will let you check that the user has entered at least a two word name, and you can also handle the case that someone enters one or more middle names or initials:
full_name = input("Please enter your name: ").lower().split()
if len(full_name) > 1:
first_letter = full_name[0][0]
three_letters_surname = full_name[-1][:3].rjust(3, 'x')
number = '{:03d}'.format(random.randrange (1,999))
username = '{}{}{}'.format(first_letter, three_letters_surname, number)
print(username)
else:
print('Error. Please enter first name and surname')
# try again...
Should a surname be less than 2 characters long (not uncommon), the name is left padded with x
characters.
Some examples:
Input Output John Wayne jway014 J J Cool jcoo777 L Ron Hubbard lron666 Bob Lo bxlo001
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With