检查字符是否在字符串Python中

2024-09-26 18:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

from decimal import *
errors = "abcdffghijklmnopqrstuvwxyz?><:;\|{}[]"
purchase_price = Decimal(input("Please enter the price of your item"))
while purchase_price in errors:
    print("Please enter the price of your item ex: 123.45")
    break
else:

我在检查errors变量中是否输入了一个或多个字符时遇到了问题。在

当输入不是数字时

输出为:

^{pr2}$

如果有一个角色在那里,我想写一个循环,给他们另一个机会重新输入价格。在


Tags: ofthefromimportinputyourpurchaseitem
2条回答

如果您希望输入是一个数字,我建议将其设为浮点,并在无法解析时处理异常:

try:
    purchase_price = float(input("Please enter the price of your item"))
except (ValueError, TypeError) as e:
    pass # wasn't valid, print an error and ask them again.

不过,请注意,浮动不是一个很好的方式来准确处理金钱!这是一笔大买卖!您需要在线搜索以找到一个好的解决方案:http://code.google.com/p/python-money/

from decimal import *

def ask():
    input_str = input("Please enter the price of your item");
    try:
        number = Decimal( imput_str )
        return number
    except( InvalidOperation, ValueError, TypeError ) as e:
        return ask()


number = ask()

相关问题 更多 >

    热门问题