简体   繁体   中英

How to convert numbers in a string to underline as output

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM