making string comparision in python

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

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 == to work but >,< seems to wokrk.How does python know that by <,> i mean the length of string without using len()

def strcmp(str1,str2):     if(len(str1) == len(str2)):      return 0     if(len(str1) > len(str2)):      return 1     if(len(str1) < len(str2)):      return -1 print strcmp("ashsih","aapam") 

vs

def strcmp(str1,str2):     if(str1 == str2):      return 0     if(str1 > str2):      return 1     if(str1 < str2):      return -1 print strcmp("ashsih","aapam") 

回答1:

< , > 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 


回答2:

Former one just compares the length of two strings. But latter one try to find which one is bigger. For instance:

A = "abcdef" B = "b" 

len(A) > len(B) will be true But B > A will be true, because "b" > "a" (which is the first letter of A)



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