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, "_"))
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)
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.
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.
"1234567890"
(and only the entire string) with a single'_'
. Are you familiar with thein
operator? If so -- use it. There are more high-tech approaches (such as regular expressions orstring.translate
) but given your level of learning to program, just use a simple loop.