如何使用len和不区分大小写?

时间:2013-03-14 02:14:01

标签: python case-insensitive

stop = False
text_count = 0
while stop is False:
    int_string = input("What is the initial string? ")
    int_string = int_string.lower()
    for a in int_string:
        for a in b:
            text_count += 1
    if text_count < 3:
        print("Error: string must have at least 3 characters.")
    elif len(int_string) != 'X' or len(int_string) != 'x' or len(int_string) != '_':
        print("Error: string must contain only X and _.")

此字符串长度必须至少为3个字符,且必须仅包含字符“X”,“x”或“_”(下划线) Case Insensitive也

2 个答案:

答案 0 :(得分:2)

您可以将其转换为set对象,并将其与您允许的字符集进行比较:

while not stop:
    int_string = input("What is the initial string? ").lower()

    if len(int_string) < 3:
        print("Error: string must have at least 3 characters.")
    elif set(int_string) <= {'x', '_'}:
        print("Error: string must contain only X and _.")

a <= ba.issubset(b)的缩写。

答案 1 :(得分:1)

这是另一个选项:

while not stop:
    int_string = raw_input("What is the initial string? ").lower()   
    if len(int_string) < 3:
        print("Error: string must have at least 3 characters.")
    elif any(ch not in ('x', '_') for ch in set(int_string)):
        print("Error: string must contain only X and _.")