简体   繁体   English

如何查找值是否包含字符

[英]How to find if the value contains characters

Right now am planning to add items into the database.现在正计划将项目添加到数据库中。 The item name, price and all are all entered by the users.商品名称、价格等全部由用户输入。 How do I find if theres any alphabets when entering the price?输入价格时如何查找是否有字母? i tried using.isnumber() but it seems to be reading my decimal point as a character as well.我尝试使用.isnumber(),但它似乎也在读取我的小数点作为一个字符。

while True:
        itemPrice = input("Please Enter Item Price: ")
        if str(itemPrice).isnumeric()  == False:
            print("Please enter a value!")
        else:
            print(itemPrice)
            break

For example, they allow if i enter 5 but not 5.5 and since this is item price it should have decimals.例如,如果我输入 5 但不是 5.5,它们允许,因为这是商品价格,它应该有小数。

You can catch exceptions,您可以捕获异常,

while True:
    itemPrice = input("Please Enter Item Price: ")
    try:
        itemPrice = float(itemPrice)
        print(itemPrice)
        break
    except ValueError:
        print("Please enter a value!")

you can use try/except block你可以使用 try/except 块

a = 3.5345
a=str(a)

try: #if it can be converted to a float, it's true
    float(a) 
    print(True)
except: # it it can't be converted to a float, it's false
    print(False)

You could try using a for loop to check:您可以尝试使用 for 循环来检查:

def containsAlpha(x):
    if True in [char.isalpha() for char in x]:
        return True
    return False

while True:
    itemPrice = input("Please Enter Item Price: ")

    if containsAlpha(itemPrice):
        print("Please enter a value!")
    else:
        print(itemPrice)
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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