首页 > 编程语言 > 详细

【python】字符串函数

时间:2015-01-30 17:16:06      阅读:250      评论:0      收藏:0      [点我收藏+]

1.String模块中的常量:

   string.digits:数字0~9

   string.letters:所有字母(大小写)

        string.lowercase:所有小写字母

        string.printable:可打印字符的字符串

        string.punctuation:所有标点

        string.uppercase:所有大写字母

 

import string
>>> string.uppercase
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘
>>> string.lowercase
‘abcdefghijklmnopqrstuvwxyz‘
>>> string.digits
‘0123456789‘
>>> string.letters
‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘
>>> string.printable
‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\‘()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c‘
>>> string.punctuation
‘!"#$%&\‘()*+,-./:;<=>?@[\\]^_`{|}~‘

 2.find函数在一个较长的字符串中查询子字符串,返回子串所在位置最左端索引,没有找到返回-1

>>> title = "Monty Python‘s Flying Circus"  
>>> title.find(‘Monty‘)  
0  
>>> title.find(‘monty‘)  
-1  
可以选择起始点和结束点
>>> title.find(‘Python‘)  
6  
>>> title.find(‘Python‘, 3)  
6  
>>> title.find(‘Python‘, 3, 10)  
-1  

 

 3.join函数在队列中添加元素(只能操作于字符串,返回一个修改后的字符串,但是原字符串不改变),它的逆函数为split,split函数将字符串分割成序列,返回该序列,原字符串不改变

>>> seq = [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]  
>>> sep = ‘+‘  
>>> sep.join(seq)  
‘1+2+3+4+5‘  
>>> seq  
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]  


>>> dirs = ‘‘, ‘usr‘, ‘bin‘, ‘env‘  
>>> ‘/‘.join(dirs)  
‘/usr/bin/env‘  
>>> print ‘C:‘ + ‘\\‘.join(dirs)  
C:\usr\bin\env  


>>> word = ‘1+2+3+4+5‘  
>>> word.split(‘+‘)  
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]  
>>> word  
‘1+2+3+4+5‘  

 4.lower函数返回字符串的小写字母版

 

>>> ‘fafDAWdfaweDWED‘.lower()  
‘fafdawdfawedwed‘  

扩展:title函数:首字母大写,其他小写
>>> "that‘s all folks".title()  
"That‘S All Folks" 

5.replace函数返回某字符串所有匹配项均被替换之后得到的字符串,原字符串不改变

>>> word = ‘this is a test‘  
>>> word.replace(‘is‘, ‘eez‘)  
‘theez eez a test‘  
>>> word  
‘this is a test

6.strip函数去除两侧(不包括内部)空格的字符串,原序列不变

>>> word = ‘   this is test    ‘  
>>> word.strip()  
‘this is test‘  
>>> word  
‘   this is test    ‘  


可在strip()加入参数,以去除想要去掉的指定字符
>>> ‘***  SPAM  *  for  *  everyone!!!  ***‘.strip(‘*‘)  
‘  SPAM  *  for  *  everyone!!!  ‘  
>>> ‘***  SPAM  *  for  *  everyone!!!  ***‘.strip(‘* ‘)  
‘SPAM  *  for  *  everyone!!!‘  

  

 

【python】字符串函数

原文:http://www.cnblogs.com/paulwinflo/p/4262420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!