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

How do I make the input case insensitive

Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
user2044600
  • 15
  • 2
  • 7

2 Answers2

4
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"
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

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

Zephyr
  • 11,891
  • 53
  • 45
  • 80
funtime
  • 652
  • 1
  • 5
  • 20