Usernames, we all have one, maybe for work or on Twitter.
How about a python program that automatically generates a username based on your name?
Sound cool? Let’s make a simple project to generate usernames.
See the live program below:
Disclaimer, this is not a python tutorial, for that, see Intro To Python.
1. Core Code
Let’s get the core elements down for the username generator.
First, displaying the title via
print() and then using two variables with
input(). Then at the end,
print() the concatenated string to combine the variables.
We’ll just comment the slicing out for now and tackle that at the next stage.
print('Welcome to the Username Generator Program.') first = input('Enter first name: ') last = input('Enter last name: ') # Slicing done here print('Your username is: ' + last + first)
Great, let’s slice out the sections of user input we need to create the username.
Now the username is based on the basic nomenclature of using the first four letters of the last name, and the first letter of the first name.
In order to program python to do this, we need to use slices.
We’ll assign the
last variables with their sliced counterparts.
last variable, it starts at the first character,
0 up to but not including
4. Then, get the first letter from the
first variable by stating
print('Welcome to the Username Generator Program.') first = input('Enter first name: ') last = input('Enter last name: ') last = last[0:4] # Slice first letter up to but not including 4 first = first # Slice first letter, starting at 0 print('Your username is: ' + last + first)
Thank you to w3schools.
3. String Conversion
The last step is to convert the concatenated output to lower case characters.
Generally, usernames are in lower case, plus this is good practice to use the
print('Welcome to the Username Generator Program.') first = str(input('Enter first name: ')) last = str(input('Enter last name: ')) last = last[0:4] # Slice first letter up to but not including 4 first = first # Slice first letter, starting at 0 print('Your username is: ' + str.lower(last) + str.lower(first)) # Change to lower case for username format
Thank you to educba.
This was a fun small project I thought of when I woke up this morning.
It’s a popular username format so it’s fun thinking about how to automate its creation. I can imagine this built into a workplace app to spit out the new hire’s username.
It’s my first time using slices outside following walkthrough projects from Automate The Boring Stuff with Python, so I’m surprised I got it so quickly.
This program only took a few minutes to complete, a lot faster than I was expecting.
This is Day 24 of #100DaysOfHacking, subscribe to the newsletter for updates and if you have feedback, message me via Twitter. Happy Hacking.