Creating User Name from Name in Python

Question:

I have a spreadsheet with data. There I have a name like Roger Smith. I would like to have the user name rsmith.
Therefore, the first letter of the first name followed by the family name. How can I do this in Python?

Asked By: OliAK

||

Answers:

def make_username(full_name: str) -> str:
    first_names, last_name = full_name.lower().rsplit(maxsplit=1)
    return first_names[0] + last_name


print(make_username("Roger M. Smith"))

Output: rsmith

The use of rsplit is to ensure that in case someone has more than one first name, the last name is still taken properly. I assume that last names will not have spaces in them.

Note however that depending on your use case, you may need to perform additional operations to ensure that you don’t get duplicates.

Answered By: Daniil Fajnberg
  • By passing the 0 index to the full name we get the first letter of the name.
  • Using the split() function we can convert the full_name into list. Then passing -1 index we can get the family name.
  • Lower() will convert the name into lower case.

full_name = 'Roger Smith'
username = full_name[0] + full_name.split()[-1]
print(username.lower())
#output : rsmith
Answered By: ch2019

Here’s an option in case you are also interested in generating usernames using last name followed by first letter of first name:

name = 'Roger R. Smith'
def user_name_generator(name,firstlast = True):
    username = name.lower().rsplit()
    if firstlast:
        username = username[0][0] + username[-1]
    else:
        username = username[-1] + username[0][0] 
    
    return username

This outputs rsmith if the parameter firstlast is set to True and outputs smithr if firstlast is set to False

Answered By: Victor Murcia

if I understand your question correctly, you want to iterate through all the names of an excel sheet in the format ‘firstletternamesurname’. This can be done with pandas, but I don’t know if that’s exactly what you want. With pandas there will be a final dataframe and you can export it to excel again. Try this:

import pandas as pd
df = pd.read_excel('name.xlsx')
for i in df:
    df1 = df['name'].iloc[0] + df['surname'].iloc[0]
    df2 = df1.split()[0]
    print(df2.lower())
Answered By: Bruhlickd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.