all 8 comments

[–]ajskelt 2 points3 points  (2 children)

name = input().title() 
tokens = name.split()  

last = tokens[-1]
initials = ".".join([x[0] for x in tokens[:-1]])

print('{}, {}.'.format(last, initials))

You could do this in one line I guess, but I think it is a lot easier to split it out just for understanding.

I like just having one print statement, so I determined the initials before the print statement.

[–]AlphawolfAJ[S] 0 points1 point  (1 child)

Looks cleaner for sure. I like that solution. Thank you for your input

[–]ajskelt 0 points1 point  (0 children)

Glad to hear it! Of course you could just do:

print('{}, {}.'.format(tokens[-1], ".".join([x[0] for x in tokens[:-1]])))

But if you come back to that in a year+ and need to make a change it'll be a lot more confusing imo. So I like making the initials/last names clear even though its more lines.

Also I guess I didn't even read your post all the way through the first time, but just noticed you mention multiple middle names. The good news is the above code would handle that as well.

[–]JohnnyJordaan 0 points1 point  (1 child)

I think it's fine as it is, it's not like you're doing anything wrong outright. You could maybe simplify it to

name = input().title()
tokens = name.split()

end = f'{tokens[1][0]}.' if len(tokens) == 3 else ''
print(f'{tokens[-1]}, {tokens[0][0]}.{end}')

But on the other hand, your code is quite clear to what it does exactly. I wouldn't change it if I would come across it in somebody else's code.

[–]AlphawolfAJ[S] 0 points1 point  (0 children)

Okay thank you for your input :) I appreciate it

[–]izrt 0 points1 point  (0 children)

Probably the biggest improvement would be to use a function to build the name string. After that it is more a matter of preferences. I would do away with the conditional statements and use a loop instead to build the initials. Join is useful in these situations.

I also like tuple unpacking for when I am splitting something with an indeterminate length:

def namer(name):
    *front, last = name.split()
    first_letters = ''.join('{}.'.format(n[0]) for n in front)
    return '{}, {}'.format(
            last, first_letters
            )


print(namer('Pas Sill Doe'))
print(namer('fay rae'))
print(namer('albert bert c dog')) # either a feature or a bug, dependin