下面是在看python核心编程中序列字符串中提到的一些函数,根据自己的学习理解总结了下,方便日后用到的时候查看。

   1、string.capitalize()

把字符串的第一个字符大写

例子:    a = 'name is : '
                print a.capitalize()  ==》Name is :

2、string.count(str, beg=0, end = len(string))

  返回str 在string 里面出现的次数,如果beg 或者end 指定则返回指定范围内str 出现的次数

例子:

a = 'test plan is to show the plan of the project. '

print a.count('plan')       #==> 2
        print a.count('plan',9,18)  #==> 0

3、string.decode(encoding='UTF-8',errors='strict')

以encoding 指定的编码格式解码string,如果出错默认报一个ValueError 的异常, 除非errors 指定的是'ignore'  或者'replace'

   4、string.encode(encoding='UTF-8',errors='strict')

以encoding 指定的编码格式编码string,如果出错默认报一个ValueError 的异常,除非errors 指定的是'ignore' 或者'replace'

5、检查字符串是否以某一字符开头或结尾
    string.endswith(obj, beg=0,end=len(string)): 检查字符串是否以obj 结束,如果beg 或者end 指定则检查指定的范围内是否以obj 结束,如果是,返回True,否则    返回False.

string.startswith(obj, beg=0,end=len(string)): 检查字符串是否是以obj 开头,是则返回True,否则返回False。如果beg 和end 指定值,则在指定范围内检查.

例:
    a = 'test plan is to show the plan of the project.'
    print a.endswith('et')          #==> False
    print a.endswith('t.')          #==> True
    print a.endswith('t',0,3)       #==> False
    print a.endswith('t',0,4)       #==> True

print a.startswith('et')          #==> False
    print a.startswith('te')          #==> True
    print a.startswith('te',3,8)       #==> False
    print a.startswith('sh',5)       #==> Flase

6、string.expandtabs(tabsize=8)

把字符串string 中的tab 符号转为空格,默认的空格数tabsize 是8.

例:
    a = 'what is \tyour favorite color    ?' #your 前面加了个tab符号
    print a                 #==> what is     your favorite color    ?
    print a.expandtabs()    #==> what is         your favorite color    ?
    print a.expandtabs(2)   #==> what is   your favorite color    ?

7、字符串中查找某一字符或字符串是否存在: string.find() 与 string.rfind()

string.find(str, beg=0,end=len(string)) 检测str 是否包含在string 中,如果beg 和end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1

例:
        a = 'what is \tyour favorite color    ?'
        print a.find('str')        #==> -1
        print a.find('\t')        #==> 8
        print a.find('your')        #==> 9        
        print a.find('your', 1,5)    #==> -1

string.rfind(str, beg=0,end=len(string))类似于find()函数,不过是从右边开始查找.

print a.rfind('your')        #==> 9    
        print a.rfind('a')        #==> 15       从右边开始找到的是favorite中的a
        print a.find('a')        #==> 2       从左边开始找到的是what中的a

  8、 字符串中查找某一字符所在的位置: string.index()与string.rindex

string.index(str, beg=0,end=len(string)) 跟find()方法一样,只不过如果str 不在string 中会报一个异常.
    string.rindex( str, beg=0,end=len(string)) 类似于index(),不过是从右边开始.

例:
        a = 'what is \tyour favorite color    ?'
        print a.index('a')        #==> 2       从左边开始找到的是what中的a
        print a.rindex('a')        #==> 15       从右边开始找到的是favorite中的a

9、字符串数值判断

string.isalnum(): 如果string 至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False

string.isalpha(): 如果string 至少有一个字符,并且所有字符都是字母则返回True,否则返回False

string.isdecimal(): 如果string 只包含十进制数字则返回True 否则返回False. 只适用于unicode字符

string.isdigit(): 如果string 只包含数字则返回True 否则返回False.

string.isnumeric()b, c, d 如果string 中只包含数字字符,则返回True,否则返回False。 只适用于unicode字符  
    例:
        a = 'what is \tyour favorite color    ?' #your 前面加了个tab符号
        c = 'what'
        b ='123456'
        d = '123 456'

print a.isalnum()        #==> False
        print a.isalpha()        #==> False
        print c.isalpha()        #==> True
        print a.isdigit()        #==> False
        print b.isalnum()        #==> True
        print b.isalpha()        #==> False
        print b.isdigit()        #==> True

print d.isdigit()        #==> False
        print d.isalnum()        #==> False

12、字符大小写转换、大小写判断:

string.lower() 转换string 中所有大写字符为小写.
    string.upper() 转换string 中的小写字母为大写
    string.swapcase() 翻转string 中的大小写

string.islower()b, c 如果string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False
    string.isupper()b, c 如果string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False
例:
        c = 'wh at'
        d = 'What'
        e = 'WHAT9'
        print c.isupper()        #==> False    
        print c.islower()        #==> True

print d.isupper()        #==> False
        print d.islower()        #==> False        
        print e.isupper()        #==> True
        print e.islower()        #==> False

print d.swapcase()        #==> wHAT
        print d.lower()            #==> what
        print d.upper()            #==> WHAT

13、string.isspace()b, c 如果string 中只包含空格,则返回True,否则返回False.

14、string.istitle() 与string.title

string.istitle()b, c 如果string 是标题化的(见title())则返回True,否则返回False
string.title() 返回"标题化"的string,就是说所有单词都是以大写开始,其余字母均为小写(见istitle())

例:
        e = 'WHAT9'
        
        print e.title()            #==>What9        
        titleStr = e.title()
        print e.istitle()        #==>False
        print titleStr .istitle()    #==>True

f ='123 456'
        print f.title()            #==>123 456
        titlef = e.title()
        print f.istitle()        #==>False
        print titlef .istitle()        #==>False

15、string.join(seq) Merges (concatenates)以string 作为分隔符,将seq 中所有的元素(的字符串表示)合并为一个新的字符串

例:
        a = 'test'
        b = 'paul is a tester'
        print b.join(a)
        #==> tpaul is a testerepaul is a testerspaul is a testert

16、去空格函数:strip()、lstrip()与rstrip()

string.strip([obj]) 在string 上执行lstrip()和rstrip()
    string.rstrip() 删除string 字符串末尾的空格.
    string.lstrip() 截掉string 左边的空格

17、字符串对齐函数 string.ljust()与string.rjust()

string.ljust(width)返回一个原字符串左对齐,并使用空格填充至长度width 的新字符串
string.rjust(width)返回一个原字符串右对齐,并使用空格填充至长度width 的新字符串

例:
        a = 'test'
        c=a.ljust(20)
        d=a.rjust(20)

print len(c)        #==>20
        print len(d)        #==>20
        print c == d        #==>False

print c[19]        #==> 结果输出为空
        print d[19]        #==> t

18、string.partition(str) 与 string.rpartition(str)

string.partition(str) 有点像find()和split()的结合体,从str 出现的第一个位置起,把字符串string 分成一个3 元素的元组(string_pre_str,str,string_post_str), 如果string 中不包含str 则string_pre_str == string, str和string_post_str均为空

string.rpartition(str)e 类似于partition()函数,不过是从右边开始查找. 如果string 中不包含str 则string_post_str == string, str和string_pre_str均为空
    例:
        a = 'This is a example for string.partition or string.rpartition'

print a.partition('or')    
            #==> ('This is a example f', 'or', ' string.partition or string.rpartition')

print a.rpartition('or')
            #==> ('This is a example for string.partition ', 'or', ' string.rpartition')

print a.partition('or1')
            #==>('This is a example for string.partition or string.rpartition', '', '')
        print a.rpartition('or1')
            #==>('', '', 'This is a example for string.partition or string.rpartition')

19、string.replace(str1, str2,num=string.count(str1))

把string 中的str1 替换成str2,如果在string中找不到str1,则不替换。如果num 指定,则替换不超过num 次.

例:
        a = 'This is a example for string.partition or string.rpartition'

print a.replace('or','OR')
            #==>This is a example fOR string.partition OR string.rpartition

print a.replace('or','OR',1)
            #==>This is a example fOR string.partition or string.rpartition

20、string.split(str="", num=string.count(str)): 以str 为分隔符切片string,如果num有指定值,则仅分隔num 个子字符串

例:
        print a.split('or')
        print a.split('or',1)
        print a.split('or1')

==>['This is a example f', ' string.partition ', ' string.rpartition']
           ['This is a example f', ' string.partition or string.rpartition']
              ['This is a example for string.partition or string.rpartition']

21、string.splitlines(num=string.count('\n')): 按照行分隔,返回一个包含各行作为元素的列表,如果num 指定则仅切片num 个行.

22、string.translate(str, del=""): 根据str 给出的表(包含256 个字符)转换string 的字符,要过滤掉的字符放到del 参数中

例:
        from string import maketrans
        d = 'What'
        intab ='at'
        outtab = '14'
        trantab = maketrans(intab,outtab)

print d.translate(trantab)        #==> Wh14

print d.translate(trantab,'a')        #==> Wh4
    
   23、string.zfill(width) 返回长度为width 的字符串,原字符串string 右对齐,前面填充0
    例:
        d = 'What'
        print d.zfill(8)        #==>0000What

Python学习之字符串函数的更多相关文章

  1. Python正则替换字符串函数re.sub用法示例(1)

    本文实例讲述了Python正则替换字符串函数re.sub用法.分享给大家供大家参考,具体如下: python re.sub属于python正则的标准库,主要是的功能是用正则匹配要替换的字符串然后把它替 ...

  2. Python学习笔记之函数

    这篇文章介绍有关 Python 函数中一些常被大家忽略的知识点,帮助大家更全面的掌握 Python 中函数的使用技巧 1.函数文档 给函数添加注释,可以在 def 语句后面添加独立字符串,这样的注释被 ...

  3. Python 学习:常用函数整理

    整理Python中常用的函数 一,把字符串形式的list转换为list 使用ast模块中的literal_eval函数来实现,把字符串形式的list转换为Python的基础类型list from as ...

  4. python学习道路(day4note)(函数,形参实参位置参数匿名参数,匿名函数,高阶函数,镶嵌函数)

    1.函数 2种编程方法 关键词面向对象:华山派 --->> 类----->class面向过程:少林派 -->> 过程--->def 函数式编程:逍遥派 --> ...

  5. Python学习笔记-字符串

    Python之使用字符串 1.所有的标准序列操作(索引,分片,乘法,判断成员资格,求长度,取最小值,最大值)对字符串同样适用.但是字符串都是不可变的. 2.字符串格式化使用字符串格式化操作符即%. f ...

  6. 小甲鱼:Python学习笔记003_函数

    >>> # 函数>>> def myFirstFunction(params1,params2...): print("这是我的第一个函数!") ...

  7. Python学习(二):函数入门

    1.函数代码格式: def 函数名(): 函数内容 执行函数:函数名() 2.代码举例: #!/usr/bin/env python #coding=utf-8 #定义函数 def Func1(): ...

  8. python 学习笔记 字符串和编码

    字符编码:因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理,最早的计算机在设计时采用8个比特(bit)作为一个字节 (byte),所以,一个字节能表示的最大的整数是255(二进 ...

  9. python学习笔记——字符串

    类方法string.upper(str)需要引入string模块,实例方法str.upper()不需要引入string模块 无与伦比的列表解析功能 # coding=utf-8 # 列表解析 prin ...

随机推荐

  1. javascript中算术运算符规则

    javascript中提供了几种算术运算符,+(加)  -(减)  *(乘)  /(除)  %(余),常规用法与数学上的一致:  但还规定一些特殊规则: 注:JavaScript中保存数值的方式,可以 ...

  2. 蓝桥杯试题集【Java】

    一.Fibonacci数列 问题描述 Fibonacci数列的递推公式为:Fn=Fn-1+Fn-2,其中F1=F2=1. 当n比较大时,Fn也非常大,现在我们想知道,Fn除以10007的余数是多少. ...

  3. CS0016: 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\921bbfc4\ca7cf42\App_Code.fu98jwep.dll”--“拒绝访问。 ”

    在本地开发环境没问题,但是发布到服务器出现:未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Fil ...

  4. Html页面加回滚

    <div class="top-box"> <img src=" class="youlink-img" /><br / ...

  5. 在FL2440上使用kei MDK 调试程序(J-link)

    <一>新建一个工程 单击Project ->New µVision Project...菜单项 <二>选择CPU 这里我们选择三星的2440A 点击OK后会提示你是否添加 ...

  6. discuz_style_default.xml 修改

    <?xml version="1.0" encoding="ISO-8859-1"?> <root> <item id=" ...

  7. 多名Uber司机被指刷单遭封号 一周薪水为0

    昨天,一司机在Uber“司机之家”办公地墙上写了泄愤的话 摄/法制晚报记者 苏妮 司机展示的账单显示,上周的薪水几乎为零,上面用英文标注了“欺诈行为”的字样 摄/法制晚报记者 苏妮 法制晚报讯(记者 ...

  8. SSD磁盘,CPU居高不下,高并发的情况下,是不是mysql解析器耗费的cpu资源高?

    你看看我做的实验,这个user表是300多W纪录,普通磁盘下,消耗时间最多的是Copy to tmp table 0.81秒,当然在ssd下,这个可以减少很多很多的,第二高就是sending data ...

  9. shell编程之文本与日志过滤

    1:grep命令: grep -v  "char"  file_name 匹配不包括"char"的文本 grep -n -w "char" ...

  10. OpenCV---图片生成视频

    /** It is a batch processing interface. */ #include "stdafx.h" #include <windows.h> ...