making string comparision in python

前端 未结 2 1411
一整个雨季
一整个雨季 2021-01-29 14:03

I was trying to replicate the strcmp from c in python.I typed the former program and it worked but the latter seems to work as well?please explain the latter one.I only expected

2条回答
  •  天涯浪人
    2021-01-29 14:25

    < , > for string operands compare lexicogrphical orders, not their lengths.

    >>> 'a' < 'b'
    True
    >>> 'a' > 'b'
    False
    
    >>> 'cat' > 'banana'
    True
    >>> 'cat' < 'banana'
    False
    

    Upper-case characters are smaller than their lower-case version.

    >>> 'A' < 'a'
    True
    >>> 'A' > 'a'
    False
    

    So, your code does case-sensitive comparison.


    You can use str.casefold for case-insensitive comparsison, (Python 3.3+ only).

    >>> 'A'.casefold()
    'a'
    >>> 'A'.casefold() == 'a'.casefold()
    True
    

提交回复
热议问题