转自:http://blog.chinaunix.net/uid-25992400-id-3283846.html
任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作。
python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求:
- python的字符串属性函数
- python的string模块
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 字符串属性函数
系统版本:CentOS release 6.2 (Final)2.6.32-220.el6.x86_64
python版本:Python 2.6.6
字符串属性方法
- >>> str='string learn'
- >>> dir(str)
- ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
字符串格式输出对齐
- >>> str='stRINg lEArn'
- >>>
- >>> str.center(20) #生成20个字符长度,str排中间
- ' stRINg lEArn '
- >>>
- >>> str.ljust(20) #str左对齐
- 'stRINg lEArn '
- >>>
- >>> str.rjust(20) #str右对齐
- ' stRINg lEArn'
- >>>
- >>> str.zfill(20) #str右对齐,左边填充0
- '00000000stRINg lEArn'
大小写转换
- >>> str='stRINg lEArn'
- >>>
- >>> str.upper() #转大写
- 'STRING LEARN'
- >>>
- >>> str.lower() #转小写
- 'string learn'
- >>>
- >>> str.capitalize() #字符串首为大写,其余小写
- 'String learn'
- >>>
- >>> str.swapcase() #大小写对换
- 'STrinG LeaRN'
- >>>
- >>> str.title() #以分隔符为标记,首字符为大写,其余为小写
- 'String Learn'
字符串条件判断
- >>> str='0123'
- >>> str.isalnum() #是否全是字母和数字,并至少有一个字符
- True
- >>> str.isdigit() #是否全是数字,并至少有一个字符
- True
-
- >>> str='abcd'
- >>> str.isalnum()
- True
- >>> str.isalpha() #是否全是字母,并至少有一个字符
- True
- >>> str.islower() #是否全是小写,当全是小写和数字一起时候,也判断为True
- True
-
- >>> str='abcd0123'
- >>> str.islower() #同上
- True
- >>> str.isalnum()
- True
-
- >>> str=' '
- >>> str.isspace() #是否全是空白字符,并至少有一个字符
- True
- >>> str='ABC'
- >>> str.isupper() #是否全是大写,当全是大写和数字一起时候,也判断为True
- True
- >>> str='Abb Acc'
- >>> str.istitle() #所有单词字首都是大写,标题
- True
-
- >>> str='string learn'
- >>> str.startswith('str') #判断字符串以'str'开头
- True
- >>> str.endswith('arn') #判读字符串以'arn'结尾
- True
字符串搜索定位与替换
- >>> str='string lEARn'
- >>>
- >>> str.find('a') #查找字符串,没有则返回-1,有则返回查到到第一个匹配的索引
- -1
- >>> str.find('n')
- 4
- >>> str.rfind('n') #同上,只是返回的索引是最后一次匹配的
- 11
- >>>
- >>> str.index('a') #如果没有匹配则报错
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: substring not found
- >>> str.index('n') #同find类似,返回第一次匹配的索引值
- 4
- >>> str.rindex('n') #返回最后一次匹配的索引值
- 11
- >>>
- >>> str.count('a') #字符串中匹配的次数
- 0
- >>> str.count('n') #同上
- 2
- >>>
- >>> str.replace('EAR','ear') #匹配替换
- 'string learn'
- >>> str.replace('n','N')
- 'striNg lEARN'
- >>> str.replace('n','N',1)
- 'striNg lEARn'
- >>>
- >>>
- >>> str.strip('n') #删除字符串首尾匹配的字符,通常用于默认删除回车符
- 'string lEAR'
- >>> str.lstrip('n') #左匹配
- 'string lEARn'
- >>> str.rstrip('n') #右匹配
- 'string lEAR'
- >>>
- >>> str=' tab'
- >>> str.expandtabs() #把制表符转为空格
- ' tab'
- >>> str.expandtabs(2) #指定空格数
- ' tab'
字符串编码与解码
- >>> str='字符串学习'
- >>> str
- '\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0'
- >>>
- >>> str.decode('utf-8') #解码过程,将utf-8解码为unicode
- u'\u5b57\u7b26\u4e32\u5b66\u4e60'
-
- >>> str.decode('utf-8').encode('gbk') #编码过程,将unicode编码为gbk
- '\xd7\xd6\xb7\xfb\xb4\xae\xd1\xa7\xcf\xb0'
- >>> str.decode('utf-8').encode('utf-8') #将unicode编码为utf-8
- '\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0'
字符串分割变换
- >>> str='Learn string'
- >>> '-'.join(str)
- 'L-e-a-r-n- -s-t-r-i-n-g'
- >>> l1=['Learn','string']
- >>> '-'.join(l1)
- 'Learn-string'
- >>>
- >>> str.split('n')
- ['Lear', ' stri', 'g']
- >>> str.split('n',1)
- ['Lear', ' string']
- >>> str.rsplit('n',1)
- ['Learn stri', 'g']
- >>>
- >>> str.splitlines()
- ['Learn string']
- >>>
- >>> str.partition('n')
- ('Lear', 'n', ' string')
- >>> str.rpartition('n')
- ('Learn stri', 'n', 'g')