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

Write a function called get_numerals that returns a list of numbers from a string

Write a function called get_numerals. get_numerals should
accept one parameter, a string. It should return a string
containing only the numerals from the original string:
no letters, punctuation marks, or spaces.

Remember, numerals have ordinal numbers between 48 ("0")
and 57 ("9"). You may use the ord() function to get
a letter’s ordinal number.

Your function should be able to handle strings with no
numerals (return an empty string) and strings with all
numerals (return the original string). You may assume
we’ll only use regular characters (no emojis, formatting
characters, etc.).

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

Write your function here!

def get_numerals(a_string):
    for char in a_string:
        if ord(char) >= 48 or ord(char) <= 57:
            a_string = a_string.replace(char, "")
    return a_string

Below are some lines of code that will test your function.
You can change the value of the variable(s) to test your
function with different inputs.

If your function works correctly, this will originally
print:
1301

8675309

print(get_numerals("CS1301"))
print(get_numerals("Georgia Institute of Technology"))
print(get_numerals("8675309"))

I have tried this multiple ways and the result is that my function only returns empty strings. I know I am missing something simple. Any help is appreciated.

>Solution :

Every number is >= 48 or <= 57. You want to remove chars with ord < 48 or > 57:

def get_numerals(a_string):
    for char in a_string:
        if ord(char) < 48 or ord(char) > 57:
            a_string = a_string.replace(char, "")
    return a_string
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