2013-03-14 138 views
-3
int_string = input("What is the initial string? ") 
int_string = int_string.lower() 

怎样使输入不区分大小写如何区分大小写?

+2

Python的?如果是这样,请添加标签 - 同样,解释“什么不行”。 – 2013-03-14 02:38:42

+0

是的python,不区分大小写 – user2044600 2013-03-14 02:39:59

+1

什么是“不区分大小写”?区分大小写仅适用*比较时 - 并且在提供的代码中没有比较。 – 2013-03-14 02:41:07

回答

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? ")) 

如果你不喜欢所有的重复代码,你可以利用total_ordering填补了一些这样的方法。

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 

测试用例:

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

问题是由于输入()函数声明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. 

所以,简单地使用的raw_input()和一切工作正常

+1

假设OP使用Python2 – 2013-03-14 02:54:42