Issue
This Content is from Stack Overflow. Question asked by grom
I have to take a string with info about a person in the format LAST, FIRST (BIRTH-DEATH) to first, last, age. i.e. print(biotoage(“Last, First (1912-1954)”)) turns into First Last, 42.
This is the code I currently have:
def bio_to_age(bio: str) -> str:
count = 0
# loop for search each index
for i in range(0, len(bio)):
# Check each char
# is comma or not
if bio[i] == ",":
count += 0
firstName = bio[0:count]
lastName = bio[count:]
numAge = 2022-1945
return firstName, lastName, numAge
Its not working to count the first and last names, which are case sensitive, and I do not know how to do the year either.
Thank you!
Solution
It’s much easier to do this using the split
function. Assuming that there are no extraneous spaces, we could do the following.
def bio_to_age(bio: str) -> str:
current_yr = 2022
last,first,yrs = bio.split() # split string by spaces
last = last[:-1] # remove comma at end of first segment
yrs = yrs[1:-1] # remove lead and closing parentheses
start,end = yrs.split('-') # split years segment by "-"
start = int(start)
if end == '': # if no death year is given
end = current_yr
else: # if death year is given
end = int(end)
return f"{first} {last}, {end - start}"
print(bio_to_age("Adle, Leo (1945-)"))
print(bio_to_age("Adle, Leo (1945-2000)"))
The resulting outputs are Leo Adle, 77
and Leo Adle, 55
.
Here’s a version that accounts for an optional middle name
def bio_to_age(bio):
tokens = bio.split() # split string by spaces
if len(tokens) == 3:
last,first,yrs = tokens
else:
mid,last,first,yrs = tokens
last = last[:-1]
yrs = yrs[1:-1] # remove lead and closing parentheses
start,end = yrs.split('-') # split years segment by "-"
start = int(start)
if end == '':
end = 2022
else:
end = int(end)
if len(tokens) == 3:
return f"{first} {last}, {end - start}"
return f"{first} {mid} {last}, {end - start}"
print(bio_to_age("Adle, Leo (1945-)"))
print(bio_to_age("Adle, Leo (1945-2000)"))
print(bio_to_age("Allie Jackie, Allegra (1945-)"))
This Question was asked in StackOverflow by grom and Answered by Ben Grossmann It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.