Often times data is not always exactly in the format you need. For this exercise you will write a
function in Python that parses a string containing a name into its constituent parts: a first name and a last
name. What makes this exercise interesting is that the name string may be formatted in one of
two ways:
"Last, First"
"First Last"
To complete this exercise, you should create a function and comment appropriately. For technical
inspiration look at the in operator, split, and find string methods.
Code:
Code as text:
def parseName(name):
''' this functions parses a name string into two strings of
first and last name.
Input: a string containing name formatted
Return: two strings containing first and last name
'''
# check if name has "," in it, if yes then split by ","
if name.find(',') != -1:
last, first = name.split(', ')
else: # else split by space " "
first, last = name.split(' ')
return first, last # return first and last names
# test the function
name = input("Enter name: ")
first, last = parseName(name)
print("The name is: ", first, last)
Sample run:
P.s. ask any doubts in comments and don't forget to rate the answer.
'1 HIT +5: def parseName (name) : this functions parses a name string into two strings of first and last name. Input: a string containing name formatted Return: two strings containing first and last name, # check if name has "," in it, if yes then split by "," if name.find(',') != -1: last, first = name.split(, '), else: # else split by space "" first, last = name.split(" "); return first, last # return first and last names # test the function print('Test 1') first, last = parseName("Jane Doe") # name space seperated print('First name: ', first) print('Last name: ', last) print('Test 2') first, last = parseName('Doe, Jane') # name comma seperated print('First name: ', first) print('Last name: ', last) 24 25 26
Test 1 First name: Jane Last name: Doe Test 2 First name: Jane Last name: Doe
Get Answers For Free
Most questions answered within 1 hours.