Home > Software design >  Replace all digits with underscores
Replace all digits with underscores

Time:01-05

I'm having trouble getting my program to produce the results in my function. The intention is to replace all digits with an underscore given user input. What am I doing wrong?

def checknum(str_input):
    for c in str_input: # loop for each characters in the string entered
    if c.isdigit(): # loop for each characters checking for digits
        change = '_'
        result = str_input.replace(c, change)
str_input = input("Enter in a string: ")
print (f'Output: {result}')

CodePudding user response:

It is easier to use regex because it does not modify your original string. Thanks for pointing it out @Jan Wilamowski .

import re

def checknum(str_input):
    return re.sub(r"\d", "_", str_input)

str_input = input("Enter a string: ")
print(checknum(str_input))

CodePudding user response:

Here result is a variable where you need to return . you print 'result' outside the function that's why you don't get any output and you must call the function which you implemented. Now back to your solution, the value of str_input has to be replaced by underscore where the digit value will found then update and assign it to str_input variable. #NB: Make sure the code indentation. Here is the solution bellow,

def checknum(str_input):
  for c in str_input: # loop for each characters in the string entered
      if c.isdigit(): # loop for each characters checking for digits
          change = '_'
          str_input = str_input.replace(c, change)
  return str_input

str_input = input("Enter in a string: ")
print (f'Output: {checknum(str_input)}')
  •  Tags:  
  • Related