如何使此代码不区分大小写?

时间:2013-09-09 22:31:34

标签: python string case-insensitive

如何制作此代码案例。不敏感?建议?

def not3(string2, string1):
    if len(string2) < 3:  return True
    if string2[:3] in string1: return False
    return not3(string2[1:], string1)

2 个答案:

答案 0 :(得分:3)

小写in个操作数:

if string2[:3].lower() in string1.lower(): return False

len()测试不受案例影响。

答案 1 :(得分:1)

通常,在将输入发送到函数之前,您可能希望将输入小写:

>>> not3('abc', 'ABCD')
True
>>> not3('abc'.lower(), 'ABCD'.lower())
False

这样,您可以在区分大小写或不区分大小写的上下文中使用相同的函数。

你也可以像这样制作一个不区分大小写的函数版本:

def not3_case_insensitive(string2, string1):
    return not3(string2.lower(), string1.lower())