The format_address
function separates out parts of the address string into new strings: house_number
and street_name
, and returns: "house number X on street named Y"
.
The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street"
, "1001 1st Ave"
, or "55 North Center Drive"
.
Fill in the gaps to complete this function.
def format_address(address_string):
# Declare variables
house_number=' '
street_name=" "
# Separate the address string into parts
x=address_string.split(" ")
# Traverse through the address parts
for y in x:
if(y.isdigit()):
house_number=y
else:
street_name+=y
street_name+=' '
# Determine if the address part is the
# house number or part of the street name
# Does anything else need to be done
# before returning the result?
# Return the formatted string
return "house number {} on street named {}".format(house_number,street_name)
print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"
But it is showing output as :
house number 123 on street named
house number 1001 on street named
house number 55 on street named
When you use str.split()
, you have the option to choose how many segments you want to split the string to (as long as it's not over the maximum). In your case, the string should only be split once, to separate the house number from the street name. Also, you can a formatted string:
def format_address(address_string):
num, st = address_string.split(' ',1)
return f"house number {num} on street named {st}"
print(format_address("123 Main Street"))
Output:
house number 123 on street named Main Street
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With