====== Python 字符串比较 ====== ===== Python 字符串简单比较 ===== 简单比较是用内置函数 cmp() 来比较两个字符串: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = "abc" >>> b = "abc" >>> cmp(a, b) 0 >>> c = "def" >>> cmp(a,c) -1 >>> ===== Python字符串比较忽略大小写 ===== ==== 正则表达式,使用IGNORECASE标志 ==== > >>> import re >>> m = re.search('multi', 'A mUltiCased string', re.IGNORECASE) >>> bool(m) True ==== 在比较前把2个字符串转换成同样大写 ==== 在比较前把2个字符串转换成同样大写,用upper()方法,或小写,lower() >>> s = 'A mUltiCased string'.lower() >>> s 'a multicased string' >>> s.find('multi') 2 ===== python 字符串高级比较===== 使用python库difflib可以实现两个字符串的比较,找到相同的部分 [[python-basic:difflib|python diff字符串比较模块]]