Home > Net >  How to replace last character in nested loops?
How to replace last character in nested loops?

Time:02-22

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!

CodePudding user response:

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)   '!')

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related