Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract non-uppercase string elements for first and last names?

I have strings of the form

NAME Firstame

and I would like to get the Firstname part. The string can be more complicated (LAST LAST2 First First2). The rule is that uppercase elements are the last name and the rest is the first name. We can assume that the first part will be upper case (= last name) and when it starts to be mixed case it is the first name until the end.

I am sure that the right regex combination of [A-Z] and \w would work. The best I came up with is

import re
re.findall('[A-Z]*\w+', 'LAST LAST2 First First2')

but it returns almost the right solution (['LAST', 'LAST2', 'First', 'First2']) :)

What would be a good way to extract this first name(s) in Python as one string?

like image 470
WoJ Avatar asked Jan 20 '26 06:01

WoJ


1 Answers

I would like to propose a non-regex solution:

string = 'LAST LAST2 First First2'
words = string.split(' ') # equals ['LAST', 'LAST2', 'First', 'First2']
result = []
for word in words:
    if not word.isupper():
        result.append(word)
print(' '.join(result))

Result:

First First2
like image 50
senshin Avatar answered Jan 23 '26 05:01

senshin



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!