9.4 - Extract forename
Problem
Write a function that will extract the forename from a full name.
Example run
Enter name: Harry Potter Forename: Harry
| 1 | Extract forename from full name | IN | fullname |
| OUT | forename |
1.1 set forname to empty string
1.2 for i from 0 to lenght of fullname -1
1.3 if fullname [current pos : current pos +1] = ” ” then
1.4 set forename to fullname[firstpos : current pos]
1.5 return forename
# Main
name = "Harry Potter"
forename = get_first_name(name)
print("Forename:", forename)
def get_first_name(full_name):
forename = ""
for i in range(len(full_name)):
if full_name[i:i+1] == " ":
forename = full_name[0:i]
return forename
# Main
name = "Harry Potter"
forename = get_first_name(name)
print("Forename:", forename)
"""
Function: get_first_name(full_name)
-----------------------------------
This function takes a full name string (e.g. "Harry Potter") as a parameter.
Steps:
1. Create an empty string called forename.
2. Loop through the full name one character at a time.
3. At each step, take a substring full_name[i:i+1]:
- This extracts exactly one character from the string.
- Compare it to " " (a space).
4. If a space is found:
- Take the substring full_name[0:i]
- This gives everything from the start up to (but not including) i
- Save it as the forename.
5. After the loop finishes, return the forename.
"""
def get_first_name(full_name):
forename = "" # start with an empty string
# loop through each character of the full name
for i in range(len(full_name)):
# check if the current character is a space
if full_name[i:i+1] == " ":
# everything before the space is the forename
forename = full_name[0:i]
return forename # give back the forename
"""
Main program
------------
1. Store a full name in a variable.
2. Call get_first_name(name) and save the result.
3. Print the returned forename.
"""
# Main
name = "Harry Potter"
forename = get_first_name(name)
print("Forename:", forename)
Extension
Update the program with a second function that will extract the surname.
| 1 | Extract forename | IN | fullname |
| OUT | forename |
| 2 | Extract surname | IN | fullname |
| OUT | surname |
Enter name: Harry Potter Forename: Harry Surname: Potter