Home > Net >  How to turn a list of names to initials
How to turn a list of names to initials

Time:06-16

I have a list of names that I need to turn to initials only, so for example ['Surname, Name'] would be NS. This is what I have done so far:

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    for name_string in name:
        split = name_string.split(", ")
        join = " ".join(split)
        initials = ""
        for n in split:
            initials  = n[0].upper()
            print(initials)

I think it's one of the last steps where I'm going wrong, any help is much appreciated

Edit: I have fixed the typo now, the names were originally in numpy.ndarray which I then turned into the list called list_names

CodePudding user response:

You can do it with a list comprehension

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
[f"{i[0].split(',')[1][1]}{i[0].split(',')[0][0]}" for i in list_names]

result:

['SJ', 'BH', 'JS']

CodePudding user response:

For splitting i have used .split(", ") comma plus space as is it included in the input list.

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    surname,name=name[0].split(', ')
    initials=name[0] surname[0]
    initials=initials.upper()
    print(initials)

I think you want output in this way:

SJ
BH
JS
  • Related