如何检查用户输入是否采用特定格式?

时间:2014-09-10 04:19:21

标签: python-2.7

我对编码非常陌生,我需要一些帮助,并且想为这样一个新手问题说抱歉,但我无法用一种方式来解决这个问题,以便轻松找到帮助,我相信在那里。无论如何,简而言之,我需要在被要求输入文本时强制用户使用格式' a = b'。

`message3 = raw_input("Enter a guess in the form a=b:")`

我想这样做,如果用户没有输入正确的格式,' a = b',会弹出一些错误消息告诉他们。

2 个答案:

答案 0 :(得分:1)

这是我将如何做到这一点,扩展我上面的评论。既然你正在学习python,那么学习python 3就是最好的。

import sys
import re

s = input("Enter a guess in the form a=b:")
matched = re.match(r'(.+)=(.+)', s)
if matched is None:
   print('enter in the form of a=b')
   sys.exit(1)
a, b = matched.groups()
print(a, b)

在正则表达式中,.+匹配非空字符串。括号是一个捕获组,因此我们可以使用a获取b.groups()

答案 1 :(得分:1)

你可以试试这个:

>>> import re
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Delirious=    # Incorrect Format
>>> m = re.match(r'.+=.+', string)
>>> try:
        if m.group():
            print "Correct Format"
    except:
        print "The format isn't correct"
"The format isn't correct"
>>>
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Me=Delirious    # Correct Format
>>> m = re.match(r'.+=.+', string)
>>> try:
        if m.group():
            print "Correct Format"
    except:
        print "The format isn't correct"
"Correct Format"