Search code examples
pythonfor-loopstring-concatenation

How to replace last character in nested loops?


I'm trying to get output to display your inputted numbers in words:

phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four",
    "5": "Five",
    "6": "Six",
    "7": "Seven",
    "8": "Eight",
    "9": "Nine"
}
output = ""
for character in phone:
    output += digits_mapping.get(character) + ", "
print(output, end="")

For example, if input is equal to 545, I will get Five, Four, Five,

How do i get Five, Four, Five!


Solution

  • Here's another strategy - check to see if you are on the last item in the list. If you are, append "!" - otherwise, append ", ".

    phone = input("Phone: ")
    digits_mapping = {
        "1": "One",
        "2": "Two",
        "3": "Three",
        "4": "Four",
        "5": "Five",
        "6": "Six",
        "7": "Seven",
        "8": "Eight",
        "9": "Nine"
    }
    output = ""
    for i in range(len(phone)):
      if i == len(phone) - 1:
        output += digits_mapping.get(phone[i]) + "!"
      else:
        output += digits_mapping.get(phone[i]) + ", "
        
    print(output, end="")