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

时间:2015-02-05 13:59:15

标签: 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:

我无法检查错误var中是否输入了一个或多个字符。

输入的内容不是数字时

输出是:

Traceback (most recent call last):
  File "C:/Users/Chris/PycharmProjects/Tax Calculator/main.py", line 4, in <module>
    purchase_price = Decimal(input("Please enter the price of your item"))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

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

2 个答案:

答案 0 :(得分:1)

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

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/

答案 1 :(得分:0)

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