简体   繁体   中英

How to make python ignore letters and only focus on numbers from the input given by the user

I finished a schoolproject, I made a calculator that calculates how high the chair and table should be to suit you after you tell it how tall you are, so it only takes numbers, but if someone types "165cm" and not just "165", it crashes. Is there a way to make python ignore the letters in that input? Or at least say something like "Sorry, only numbers are allowed" And let the user type their height again. I prefer if you write the whole final code first and then explain how it works but just one of them might work too. It's in swedish but I don't think its a problem. If you have to use längd and you don't know how to write ä you can just type a, I can fix it later. Heres the code

längd = int(input())
bord = längd*0.3883063508
stol = längd*0.2582726288
print("Bordet ska vara ", end=""),
print(round(bord), end=""),
print(" cm hög och stolen ska vara ", end=""),
print(round(stol), end=""),
print(" cm hög.", end=""),```

This code should work just fine:

import re
langd = int(re.findall("\d+", input())[0])
bord = langd * 0.3883063508
stol = langd * 0.2582726288
print("Bordet ska vara ", end="")
print(round(bord), end="")
print(" cm hög och stolen ska vara ", end="")
print(round(stol), end="")
print(" cm hög.", end="")

Command re.findall("\d+", langd) returns list of separated numbers in a string from input. Since we are only interested in the first of those numbers, we use [0] at the end of that command to take only the first element of the list.

Catch the exception, and ask for proper input.

while True:
    x = input(()
    try:
        langd = float(x)
        break
    except ValueError:
        print(f"Invalid input f{x}, try again")

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