How to make case insensitive? [closed]

核能气质少年 提交于 2019-12-13 09:50:01

问题


int_string = input("What is the initial string? ")
int_string = int_string.lower()

How do I make the input case insensitive


回答1:


class CaseInsensitiveStr(str):
    def __eq__(self, other):
        return str.__eq__(self.lower(), other.lower())
    def __ne__(self, other):
        return str.__ne__(self.lower(), other.lower())
    def __lt__(self, other):
        return str.__lt__(self.lower(), other.lower())
    def __gt__(self, other):
        return str.__gt__(self.lower(), other.lower())
    def __le__(self, other):
        return str.__le__(self.lower(), other.lower())
    def __ge__(self, other):
        return str.__ge__(self.lower(), other.lower())

int_string = CaseInsensitiveStr(input("What is the initial string? "))

If you don't like all the repetitive code, you can utilise total_ordering to fill in some of the methods like this.

from functools import total_ordering

@total_ordering
class CaseInsensitiveMixin(object):
    def __eq__(self, other):
        return str.__eq__(self.lower(), other.lower())
    def __lt__(self, other):
        return str.__lt__(self.lower(), other.lower())

class CaseInsensitiveStr(CaseInsensitiveMixin, str):
    pass

Testcases:

s = CaseInsensitiveStr("Foo")
assert s == "foo"
assert s == "FOO"
assert s > "bar"
assert s > "BAR"
assert s < "ZAB"
assert s < "ZAB"



回答2:


Problem is due to input() function as stated here

This function does not catch user errors. If the input is not syntactically valid,
a SyntaxError will be raised. Other exceptions may be raised if there is an error 
during evaluation.


Consider using the raw_input() function for general input from users.

So simply use raw_input() and the everything works fine



来源:https://stackoverflow.com/questions/15400187/how-to-make-case-insensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!