-4

I'm trying to write a function that converts all digits in a string to underline. Please where have I gone wrong?

numbers = "1234567890"

string_input = str(input("Input a String? "))

print(string_input.replace(numbers, "_"))
3
  • 3
    Your code replaces the entire string "1234567890" (and only the entire string) with a single '_'. Are you familiar with the in operator? If so -- use it. There are more high-tech approaches (such as regular expressions or string.translate) but given your level of learning to program, just use a simple loop. Apr 19, 2021 at 10:57
  • @MikeScotty Someone learning to program for the first time probably doesn't yet have the basic mental model needed to understand what they read. Your comment suggests that you have a mild case of the curse of knowledge (which is of course much better than having the curse of ignorance :)). Apr 19, 2021 at 11:04
  • @MikeScotty Brother, I am sorry I do not possess the programming knowledge you do. I am trying to learn Python but sometimes it's hard to know what you're looking for. Apr 19, 2021 at 20:35

3 Answers 3

1

Do you mean something like this?

string = "There are 5, 7, 2, and 15 foobars"

numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")

for num in numbers:
    string = string.replace(num, "_")

# "There are _, _, _, and __ foobars"
print(string)

EDIT: alternative way

string = "There are 5, 7, 2, and 15 foobars"

for num in range(10):
    string = string.replace(str(num), "_")

# "There are _, _, _, and __ foobars"
print(string)
1
  • Thank you sir. This is exactly what i was after. I just had to add user input and it worked perfectly. Apr 19, 2021 at 20:37
0

You are replacing the string "1234567890". I think what you want to do is replace every number in that string. So you would have to make a for loop and loop through every number in that string and replace it in the input string.

0

You could use a generator expression:

string_input = input("Input a String? ")
print(''.join('_' if x in '0123456789' else x for x in string_input))

Or the regex library:

import re
string_input = input("Input a String? ")
print(re.sub('\d', '_', string_input))

Btw. input(...) already returns a string, so you don't need to convert it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.