3

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?

1
  • Parsing names reliably can be tricky. But try something like: username = f"{name[0]}{name.split(maxsplit=1)[1]}".lower() Commented Aug 24, 2022 at 16:14

4 Answers 4

7
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.

Sign up to request clarification or add additional context in comments.

Comments

2
  • 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

2 Comments

Not lowercase. Also the ' ' argument to split is redundant.
@DaniilFajnberg Thank you. I have updated by code.
1

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

Comments

0

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.