Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading