'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 1:[1]

String concatenation in loops is generally a bad idea in Python (Not so bad when doing it a few times). Instead you can use a list and append the items to it. Then use .join(). For printing you need to specify the end= argument to '!\n' instead of the default '\n'.

output = [digits_mapping[char] for char in phone]
print(", ".join(output), end='!\n')

You could also use generator expression:

print(", ".join(digits_mapping[char] for char in phone), end='!\n')

Another way is to build the string with '!' then use normal print:

print(", ".join(digits_mapping[char] for char in phone) + '!')

Solution 2:[2]

Any time you are creating a character delimited list, it's best writing the members of the list to a list object and the using join() to output the delimited string. This is true in any language (although it's usually an array, not a list, that you use). Instead:

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

Solution 3:[3]

At the end just print a copy of the string, with the exception of the last 2 characters (a space and a comma: ", "), and add to your end parameter the exclamation sign you desire. Your last line would look like this:

print(output[:-2], end="!")

Solution 4:[4]

I suggest that after the for, you reassign output to itself omitting the last character(","). Then you concatenate output with "!".

output=output[0:len(output)-1]
output+="!"

I hope that I helped you. Have a nice coding session.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JNevill
Solution 3 Thermostatic
Solution 4 Pasqu