Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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="")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading