Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the int and string from a string

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  
like image 446
praneeth sunkavalli Avatar asked Dec 03 '22 09:12

praneeth sunkavalli


1 Answers

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
like image 170
Ann Zen Avatar answered Dec 16 '22 19:12

Ann Zen