-2

I am trying to separate the name from the domain name in python. I have gotten fairly close, however the output doesn't look quite right. This is what I have done thus far:

def get_name(email_list):
   x = []
   for name in email_list:
      y, _, _ = name.partition("@")
      split_name = y.split('_')
      x.append(split_name)
   return(x)

When I run this with this example of an input:

get_name(["arthur_blake@gmail.com", "bob_dylan@gmail.com"])

I get the following output:

[['arthur', 'blake'], ['bob', 'dylan']]

I want the output to look like so:

['Arthur Blake', 'Bob Dylan']

Any suggestions on how to fix this?

Amin
  • 2,605
  • 2
  • 7
  • 15

3 Answers3

0

Use str.capitalize to convert first letter to uppercase and str.join to convert a list of words into a single string.

def get_name(email_list):
   x = []
   for name in email_list:
      y, _, _ = name.partition("@")
      split_name = y.split('_')
      x.append(" ".join([n.capitalize() for n in split_name]))
   return(x)

print(get_name(["arthur_blake@gmail.com", "bob_dylan@gmail.com"]))
matszwecja
  • 6,357
  • 2
  • 10
  • 17
0

We can use str.replace and str.title to keep the name as one string and capitalize it like you want:

def get_name(email_list):
   x = []
   for name in email_list:
      y, _, _ = name.partition("@")
      full_name = y.replace('_', ' ')
      titled_name = full_name.title()
      x.append(titled_name)
   return(x)

The line y.replace('_', ' ') replaces all instances of _ with a space, turning arthur_blake into arthur blake.
The statement split_name.title() capitalizes the first letter of each word, turning arthur blake into Arthur Blake

Adid
  • 1,504
  • 3
  • 13
0

Here another solution, as quasi one-liner (I do like list comprehension):

mails = ['joe_doe@gmail.com', 'peter_parker@mail.com']

def get_name(email_list):
  return [' '.join(m.split('@')[0].split('_')).title() for m in email_list]

print(get_name(mails))
white
  • 601
  • 3
  • 8