如何使一个程序在一个原始的inpu中区分113

2024-04-26 10:24:13 发布

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

你好,这是我的密码:

def function():
    n1=1
    n2=2
    n3=3
    n4=4
    n5=5
    n6=6
    n7=7
    n8=8
    n9=9
    n10=10
    n11=11
    n12=12
    n13=13
    n = raw_input("Number (with optional text): ")
    if n1 or n2 or n3 or n4 or n5 or n6 or n7 or n8 or n9 in n:
        print "Not what I want"
    elif n12 or n13 in n:
        print "Dis I want"

function()

我试图使原始输入条件接受我在消息中输入13(因为它检测到输入有1或3),但我就是不能(请,我知道我可以在列表中创建一个范围,然后它接受我分别输入每个数字,但这是我正在开发的另一个程序代码的一部分,用户可以在其中输入他们想要的单词,只要输入这些数字,但它不能区分1或11(例如)。希望你能帮忙:)


Tags: orinfunctionprintn2n6n3n1
3条回答
if '12' in n or '13' in n:
    print 'OK'
else:
    print 'wrong'

如果允许集合中有更多元素,最好使用any()并理解:

if any(str(x) in n for x in range(1, 14)):
    print 'found number from range 1-13 in this string'

你有两个错误,第一个是原始输入返回字符串,你需要把它变成一个int。你知道吗

n = raw_input("Number (with optional text): ")
k = int(n)  
if k in [n1, n2, n3]:
    print "Not what I want"
elif k in [n12, n13]:
    print "Dis I want"

由于OP显然想从raw_input中获取数字,我认为如果使用in作为条件检查,就有一个逻辑问题,例如,您希望“blah blah 9 blah”检查9在1-13之间,但是使用in将使这个“blah blah 999 blah”在1-13之内通过9的条件,因为if "9" in n已经返回了True。我不认为这是OP想要的结果。你知道吗

因此,我建议使用reraw_input中取出第一个数字并进行检查。像这样:

import re


def check_number_ok():
    n1, n2, n3, ... = 1, 2, 3, ... # you can assign n1 to n13 like this too
    n = raw_input("Number (with optional text): ")
    check_number = re.compile('\d+')
    check_result = check_number.search(n)
    if check_result is not None:
        first_number = int(check_result.group())
        if first_number == n1:
            # do something here
        elif first_number == n2:
            # do another thing
        # ... check if any others match
        else:
            print "Not what I want"
            return
            # do exit thing here so below code will not run
        # if code runs here which means it passes the check
        print "Dis I want"
    else:
        print "Please at least enter something with a number"

用法:

check_number_ok()
Number (with optional text): hello 2 world
Dis I want

check_number_ok()
Number (with optional text): the cat is out 111
Not what I want

相关问题 更多 >