繁体   English   中英

给定 python 中字符串中的一组数字

[英]Given set of numbers in a string in python

我想检查字符串中是否存在一组数字

这是我的代码:

def check_no(string):
    string = string.lower()
    no = set(c)

    s = set()
    for i in string:
        if i in no:
            s.add(i)
        else:
            pass

    if len(s) == len(no):
        return("Valid")
    else:
        return("Not Valid")

c = input()
print(check_no(c))

如果字符串中存在给定的一组数字,则打印Valid ,如果不存在,则打印Not valid

当输入为123并且字符串就像I have 12 car and 3 bikes时,程序运行良好,那么 output 是有效的

但是当我将输入作为254并将字符串作为i hav25555number时,output 是valid的,但实际的 output 应该是Not valid的,因为字符串中不存在4

任何人都可以帮助如何在提供的代码中解决它

我要检查所有字符是否匹配,然后使用all

def check_no(text, check):
    valid =  all(character in text for character in check)
    if valid:
        return("Valid")
    else:
        return("Not Valid")

check = '254'
text = 'i hav25555number'
print(check_no(text, check))

单线版本

def check_no(text, check):
    return 'Valid' if all(character in text for character in check) else 'Not Valid'

您的 function 大部分是正确的,但可能是因为您(可怕的)变量名称选择, stringc变量在环境中混淆了。

解决方案是将参数显式添加到 function 定义中(也避免使用stringc类的名称,因为这些可能是预定义的 python 关键字):

teststring = "254"
testc = "i hav25555number"

def check_no(mystring, myc):
    string = mystring.lower()
    no = set(c)
    print("string is",string)
    s = set()
    for i in string:
        
        if str(i) in no:
#            print(i, " in ", no)
            s.add(i)
        else:
            pass
#        print("s is",s)
#        print("no is",no)
    if len(s) == len(no):
        return("Valid")
    else:
        return("Not Valid")

print(check_no(teststring,testc))

给出:

print(check_no(teststring,testc))
string is 254
Not Valid

如前所述,您可以使用all使您的代码更优雅,尽管您的实现也没有任何问题。

暂无
暂无

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

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