2
votes

Changer l'int et la chaîne d'une chaîne

La fonction format_address sépare les parties de la chaîne d'adresse en de nouvelles chaînes: numéro_maison et nom_rue, et renvoie: "numéro de maison X sur la rue nommée Y". Le format de la chaîne d'entrée est: numéro de maison numérique, suivi du nom de la rue qui peut contenir des chiffres, mais jamais par eux-mêmes, et peut comporter plusieurs mots. Par exemple, «123 Main Street», «1001 1st Ave» ou «55 North Center Drive». Remplissez les espaces pour terminer cette fonction.

house number 123 on street named  
house number 1001 on street named  
house number 55 on street named  

Mais il affiche la sortie comme:

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"


1 commentaires

@TomServo Je pensais qu'avec la syntaxe {} il suffit de la remplir de gauche à droite


12 Réponses :


4
votes

il me semble que votre déclaration de return se produit dans la boucle for , ce qui signifie que vous quittez la boucle après seulement le premier élément! Mais à ce moment-là, vous n'avez pas encore identifié le nom de la rue.

Déplacez simplement le return ... d'un onglet en arrière et cela devrait fonctionner correctement.


1 commentaires

Bon endroit! Ceci est un bon exemple de la raison pour laquelle garder vos commentaires alignés avec le code qu'ils commentent est une bonne pratique; il est vraiment difficile de suivre visuellement la ligne verticale de l'indentation car les commentaires sont partout.



0
votes

C'est parce que votre retour n'est pas dans la bonne indentation. Il est appelé dans la première boucle, donc votre boucle pour n'a fait qu'une seule itération.

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"```


0 commentaires

4
votes

Lorsque vous utilisez str.split() , vous avez la possibilité de choisir le nombre de segments dans str.split() vous souhaitez fractionner la chaîne (à condition qu'elle ne dépasse pas le maximum) . Dans votre cas, la chaîne ne doit être divisée qu'une seule fois, pour séparer le numéro de maison du nom de la rue. En outre, vous pouvez une chaîne formatée:

house number 123 on street named Main Street

Production:

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"))


1 commentaires

Très belle réponse, et va au-delà de la simple correction directe du bug évident.



0
votes

Ou vous pouvez simplement le faire!

def format_address(address_string):
  # Declare variables
  space = address_string.find(" ")
  house_number = address_string[:space]
  street_name = address_string[space:]
  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"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"


0 commentaires

0
votes
def format_address(address_string):
  house_number =''
  street_name =''

  # Declare variables

  # Separate the address string into parts
  spi = address_string.split()
  # Traverse through the address parts
  for ele in spi:
    if ele.isdigit():
      house_number = ele
    else:
      street_name += ele
      street_name += ' '
`

`# 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"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"`

0 commentaires

0
votes
def format_address(address_string):
  # Declare variables
  addres = address_string.split()
  count = 0
  stret= ""
  for x in addres:
    if count == 0:
      num = x
      count+=1
    elif count == 1:
      stret += x
      count+=1
    else:
      stret += " "
      stret += x
      count+=1

  # Does anything else need to be done 
  # before returning the result?
  
  # Return the formatted string  
  return "house number {} on street named {}".format(num, stret)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"

0 commentaires

1
votes
def format_address(address_string):
  # Declare variables
  number = ''
  street = ''
  # Separate the address string into parts
  address_string = address_string.split()
  # Traverse through the address parts
  for add in address_string:
      # Determine if the address part is the
      # house number or part of the street name
      if add.isdigit():
          number += add 
      # Does anything else need to be done 
      # before returning the result?
      else :
          street += " " + add
      # Return the formatted string  
      return "house number {} on street named {}".format(number, street)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"

0 commentaires

0
votes

Cela fonctionne pour moi

def format_address(address_string):
    # Declare variables
    hn =""
    ha =""
  # Separate the address string into parts
    address_string = address_string.split()
  # Traverse through the address parts
    for add in address_string:
        if add.isnumeric():
            hn += add
        else:
            ha += add + " "
    # 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(hn,ha)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"


0 commentaires

1
votes
def format_address(address_string):
  # Declare variables
  house_number = 0
  street_name = []
  # Separate the address string into parts
  address = address_string.split()
  # Traverse through the address parts
  for item in address:
    if item.isnumeric():
      house_number = item
    else:
      street_name.append(item)
    # 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, " ".join(street_name))

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"

0 commentaires

0
votes
def format_address(address_string):
# Declare variables
  house_number=[]
  street_name=[]
  addresses=[]
# Separate the address string into parts
  addresses = address_string.split()
# Traverse through the address parts
  for address in addresses:
# Determine if the address part is the house number or part of the street name
    
    if address.isnumeric() == True:
       house_number.append(address)
    else:
       street_name.append(address)
  
  house=" ".join(house_number)
  street=" ".join(street_name)
# Return the formatted string  
  return "house number {} on street named {}".format(house,street)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"

print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"

0 commentaires

0
votes
def format_address(address_string):
  words = address_string.split()
  return "house number {} on street named {}".format(words[0],' '.join(words[1:]))

0 commentaires

0
votes
def format_address(address_string):
# Declare variables
house_number=''
street_name=''
# Separate the address string into parts
address = address_string.split()
# Traverse through the address parts
for add in address:
    # Determine if the address part is the
    # house number or part of the street name
    if add.isnumeric():
        house_number = int(add)
    else:
        street_name += add + " "
        # 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.strip())

1 commentaires

Salut Ghyxen. Bienvenue dans Stack Overflow. Bien que ce code puisse répondre à la question, fournir un contexte supplémentaire concernant la raison et / ou la manière dont ce code répond à la question améliore sa valeur à long terme. Comment répondre . De plus, il y a beaucoup de réponses à cette question. Pouvez-vous expliquer pourquoi je devrais utiliser celle-ci plutôt que l'une des réponses existantes. Sincères amitiés.