这里会显示出您选择的修订版和当前版本之间的差别。
python-basic:string-compare [2010/06/02 01:18] |
python-basic:string-compare [2010/06/02 01:18] (当前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== Python 字符串比较 ====== | ||
+ | ===== Python 字符串简单比较 ===== | ||
+ | 简单比较是用内置函数 cmp() 来比较两个字符串: | ||
+ | <code python> | ||
+ | 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 | ||
+ | >>> | ||
+ | </code> | ||
+ | |||
+ | |||
+ | ===== Python字符串比较忽略大小写 ===== | ||
+ | |||
+ | ==== 正则表达式,使用IGNORECASE标志 ==== | ||
+ | <code python>> | ||
+ | >>> import re | ||
+ | >>> m = re.search('multi', 'A mUltiCased string', re.IGNORECASE) | ||
+ | >>> bool(m) | ||
+ | True | ||
+ | </code> | ||
+ | |||
+ | ==== 在比较前把2个字符串转换成同样大写 ==== | ||
+ | |||
+ | <code python> | ||
+ | 在比较前把2个字符串转换成同样大写,用upper()方法,或小写,lower() | ||
+ | >>> s = 'A mUltiCased string'.lower() | ||
+ | >>> s | ||
+ | 'a multicased string' | ||
+ | >>> s.find('multi') | ||
+ | 2 | ||
+ | </code> | ||
+ | ===== python 字符串高级比较===== | ||
+ | 使用python库difflib可以实现两个字符串的比较,找到相同的部分 | ||
+ | |||
+ | [[python-basic:difflib|python diff字符串比较模块]] | ||
+ | |||
+ | |||