Reputation: 305
I'm trying to compare 2 last names and see which comes first in alphabetical order
How would I extract the second word in any string with [firstword: secondword] format?
Upvotes: 0
Views: 85
Reputation: 11326
The most appropriate way to do this is to use split() function:
Return a list of the words in the string, using sep as the delimiter string.
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
For instance:
>>> name = "Grace Hopper"
>>> name = name.split()
>>> name
>>> ["Grace", "Hopper"]
If you want to compare by alphabetical order several strings, just use one of the comparison operators:
>>> name1 = "Stan"
>>> name2 = "Viktor"
>>> name1 > name2
>>> False
You're getting this result because of ord("S") < ord("V")
, ord() built-in function returns an integer representing the Unicode code point of that character.
Upvotes: 0
Reputation: 19332
To extract the last name, you can use split
to split the name. It will, by default, split on whitespace:
fullname = 'Grace Hopper'
first_name, last_name = fullname.split()
Then, to compare alphabetically, simply compare the lastnames:
if last_name_1 < last_name_2:
...
Or, use sorted
to sort all names in a list of names:
fullnames = 'Grace Hopper', 'Katherine Johnson'
sorted_fullnames = sorted(fullnames, key=lambda fullname: fullname.split()[1])
Upvotes: 1
Reputation: 3419
Use the .split
function to split string into words.
In [1]: a="Grace Hopper"
In [2]: b="Katherine Johnson"
In [3]: a.split()
Out[3]: ['Grace', 'Hopper']
In [4]: b.split()
Out[4]: ['Katherine', 'Johnson']
In [6]: a.split()[1]
Out[6]: 'Hopper'
In [8]: b.split()[1]
Out[8]: 'Johnson'
In [9]: a.split()[1] < b.split()[1]
Out[9]: True
Upvotes: 0
Reputation:
It seems you want to get the last names from the full names. If a person "1" has name "ABC DEF"; Another person "2" has name "PQR STU";
You can tokenize the string by using split() command.
person1 = "ABC DEF"
person2 = "PQR STU"
name1 = person1.split(" ")
name2 = person2.split(" ")
Now the results will be,
print(name1)
>>> ['ABC', 'DEF']
print(name2)
>>> ['PQR', 'STU']
Upvotes: 1
Reputation: 16573
Try this:
s = 'Grace Hopper Katherine Johnson'
result = min(s.split()[1::2])
print(result)
Output:
Hopper
Note that it's case sensitive (A
< a
). For a case insensitive version:
result = min(s.split()[1::2], key=str.lower)
Upvotes: 0