Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove a middle initial from a name in python?

I'm trying to figure out something that seems like it should be simple. I'm trying to remove the middle initial from names, but I'm not sure how to do it without making a replace() for every letter of the alphabet. This is what I'm looking for:

(Starts as)

"John D Smith"

"Robert B Johnson"

(Ends as)

"John Smith"

"Robert Johnson"

What is the simplest way of accomplishing the above in Python? The middle initial is random, but is always surrounded by white space.

like image 479
Matthew Avatar asked Aug 05 '26 09:08

Matthew


1 Answers

May this help, based on your post

>>> import re
>>> re.sub(' [A-Z]* ', ' ', "John D Smith")
'John Smith'
>>> re.sub(' [A-Z]* ', ' ', "Robert B Johnson")
'Robert Johnson'
like image 191
BAE Avatar answered Aug 07 '26 22:08

BAE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!