python区分大小写禁用并获取eual字符串

时间:2019-01-24 12:24:47

标签: python-3.x

def worker(queue):
    while True:
        if not queue.empty():
            words = 'BananA'
            words1 = 'nut'
            words2 = 'KreMA'
            words3 = 'KIVI'
            words4 = 'TesT'
            process(data, words, words1, words2, words3, words4)

def process(data, words, words1, words2, words3, words4):
    if (search != words):
        print("Words Not Found")
    if (words in search or words1 in search or words2 in search or words3 in search or words4 in search):
        print("Words Found  : " + str(Words) + "\n")
        file = open("finded.txt","a")
        file.write("Words Founds "+ str(words)
        file.close()

但是,如果将“ banana”更改为“ Banana”,请更改行

代码不起作用,我需要Banana或BANANA或BaNaNa相等,然后变为真,

1 个答案:

答案 0 :(得分:1)

例如,您可以始终比较小写字母:

fruits = ["apple", "baNana", "cherry"]

if "banana".lower() in map(str.lower, fruits):
   print("yes")

if "BaNanA".lower() in map(str.lower, fruits):
   print("yes2")

输出:

yes
yes2

编辑:

编辑代码后:

1) 此代码if (search != words):后跟words in search并以words = 'BananA'开头似乎无法工作-看起来相互冲突。

2) 假设您要执行的代码是if (words in search or words1 in search or words2 in search or words3 in search or words4 in search):。试试这种方式:

if (words.lower() in map(str.lower, search) or words1.lower() in map(str.lower, search) or words2.lower() in map(str.lower, search) or words3.lower() in map(str.lower, search) or words4.lower() in map(str.lower, search)):

或相同但写得好很多

search = list(map(str.lower, search))
for w in [words, words1, words2, words3, words4]:
    if w.lower() in search:
        ...

请注意,在第二种情况下,maplist括起来。这是因为映射结果是迭代器。如果没有此功能,则只能使用一次。