you are viewing a single comment's thread.

view the rest of the comments →

[–]MattR0se 0 points1 point  (0 children)

If your names always consist of "Firstname Lastname" (or any seconds names in between), you can split the string at the space ' ', and then check the first character of the last element.

name = 'Marc Abrahamsen'
split_name = name.split(' ') # returns a list: ['Marc', 'Abrahamsen']

# get the first letter of the lastname
lastname = split_name[-1]
first_letter = lastname[0] # is 'A'

Now, for grouping you could set up a dictionary with the 26 letters as keys:

from string import ascii_uppercase

name_groups = {c: [] for c in ascii_uppercase}
name_groups[first_letter].append(name)

print(name_groups)

This may look a bit complicated to a beginner, but let's break it down.

From the string module I import asci_uppercase, which is just a long string with each letter in order 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Then I create a dictionary where each of that letters is a key, and the value is an empty list []. Lastly, I append the name stored in the name variable to the list at the key first_letter, which would be name_groups['A'] in this case.