I am trying to complete a homework task and I am a little bit lost with it. I need to write a program using python where I need to enter a string and then output the string. Simple enough, but my task requires if the string has any numbers, the output will print underline instead of the number " _ ".
- Example.
input a string: hello I am 7 years old.
(REQUIRED Output: hello I am _ years old.)
So far this Is the current code i have.
string =input("Input a string? ")
print("Output:",string)
Could you please help me understand how this is achieved as I am fairly new to python.
CodePudding user response:
You can use Regex to trade out the numbers for anything.
#first I import the module
import re
#then I ask for a string
inputstring = input("Input a string? ")
#here I am taking the string and using regex. the \d does all numbers 0-9 and replaces them with the next argument which is an underscore,finally the input string is placed as the last argument.
finalstring = re.sub('\d', '_', inputstring)
#printing the final edited string
print(finalstring)