python 的字符串常用函数

1. str.capitalize()

  • 用途

    将字符串的第一个字符转换为大写。

  • 实例

    str = 'hello world'
    print(str.capitalize())
    
    
    out:
    	Hello world
    

2. str.center(width, fillchar)

  • 用途

    返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

  • 实例

    str = 'hello world'
    print(str.center(20, '*'))
    
    
    out:
    	****hello world*****
    

3. str.count(sub, start= 0,end=len(str))

  • 用途

    返回 sub 在 str 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内(左闭右开) sub 出现的次数。

  • 实例

    str = 'hello world'
    print(str.count('o', 4, 8))
    
    
    out:
    	2
    

4. bytes.decode(encoding=“utf-8”, errors=“strict”)

  • 用途

    decode() 方法以指定的编码格式解码 bytes 对象。默认编码为 ‘utf-8’。

    Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。

  • 参数

    • encoding:要使用的编码,如"UTF-8"。

    • errors:设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。

  • 实例

    str = "解码实例"
    str_utf8 = str.encode("UTF-8")
    str_gbk = str.encode("GBK")
     
    print(str)  # 
     
    print("UTF-8 编码:", str_utf8)
    print("GBK 编码:", str_gbk)
     
    print("UTF-8 解码:", str_utf8.decode('UTF-8','strict'))
    print("GBK 解码:", str_gbk.decode('GBK','strict'))
    
    
    out:
    	解码实例
    	UTF-8 编码: b'\xe8\xa7\xa3\xe7\xa0\x81\xe5\xae\x9e\xe4\xbe\x8b'
    	GBK 编码: b'\xbd\xe2\xc2\xeb\xca\xb5\xc0\xfd'
    	UTF-8 解码: 解码实例
    	GBK 解码: 解码实例
    

5. str.encode(encoding=‘UTF-8’,errors=‘strict’)

  • 用途

    以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

    如果出错默认报一个ValueError 的异常,除非 errors 指定的是’ignore’或者’replace’。

    该方法返回编码后的字符串,它是一个 bytes 对象。

  • 参数

    • encoding:要使用的编码,如"UTF-8"。

    • errors:设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。

  • 实例

    str = "编码实例"
    str_utf8 = str.encode("UTF-8")
    str_gbk = str.encode("GBK")
     
    print(str)
     
    print("UTF-8 编码:", str_utf8)
    print("GBK 编码:", str_gbk)
    
    
    out:
    	编码实例
    	UTF-8 编码: b'\xe7\xbc\x96\xe7\xa0\x81\xe5\xae\x9e\xe4\xbe\x8b'
    	GBK 编码: b'\xb1\xe0\xc2\xeb\xca\xb5\xc0\xfd'
    

6. str.endswith(suffix[, start[, end]])

  • 用途

    endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。

  • 参数

    • suffix:该参数可以是一个字符串或者是一个元素。

    • start:字符串中的开始位置,开区间。

    • end:字符中结束位置,闭区间。

  • 实例

    str = 'Hello World'
    print(str.endswith('d', 0, 10))
    print(str.endswith('d', 0, 11))
    
    
    out:
    	False
    	True
    

7. str.expandtabs(tabsize=8)

  • 用途

    expandtabs() 方法把字符串中的 tab 符号 \t 转为空格,tab 符号 \t 默认的空格数是 8,在第 0、8、16…等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足 8 的倍数则以空格代替。

    该方法返回字符串中的 tab 符号 \t 转为空格后生成的新字符串。

  • 参数

    • tabsize:指定转换字符串中的 tab 符号 \t 转为空格的字符数。
  • 实例

    str = "runoob\t12345\tabc"  
    print('原始字符串:', str)
     
    # 默认 8 个空格
    # runnob 有 6 个字符,后面的 \t 填充 2 个空格
    # 12345 有 5 个字符,后面的 \t 填充 3 个空格
    print('替换 \\t 符号:', str.expandtabs())
     
    # 2 个空格
    # runnob 有 6 个字符,刚好是 2 的 3 倍,后面的 \t 填充 2 个空格
    # 12345 有 5 个字符,不是 2 的倍数,后面的 \t 填充 1 个空格
    print('使用 2 个空格替换 \\t 符号:', str.expandtabs(2))
     
    # 3 个空格
    print('使用 3 个空格:', str.expandtabs(3))
     
    # 4 个空格
    print('使用 4 个空格:', str.expandtabs(4))
     
    # 5 个空格
    print('使用 5 个空格:', str.expandtabs(5))
     
    # 6 个空格
    print('使用 6 个空格:', str.expandtabs(6))
    
    
    out:
    	原始字符串: runoob      12345   abc
    	替换 \t 符号: runoob  12345   abc
    	使用 2 个空格替换 \t 符号: runoob  12345 abc
    	使用 3 个空格: runoob   12345 abc
    	使用 4 个空格: runoob  12345   abc
    	使用 5 个空格: runoob    12345     abc
    	使用 6 个空格: runoob      12345 abc
    

8. str.find(str, beg=0, end=len(string))

  • 用途

    检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回 -1。

  • 参数

    • str:指定检索的字符串

    • beg:开始索引,默认为0,闭区间。

    • end:结束索引,开区间,默认为字符串的长度。

  • 实例

    str = 'Hello World'
    
    print(str.find('H', 0, 4))
    print(str.find('0', 0, 5))
     	
     	
    out:
    	0
    	-1
    

9. str.index(str, beg=0, end=len(string))

  • 用途

    检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

    如果包含子字符串返回开始的索引值,否则抛出异常。

  • 参数

    • str:指定检索的字符串

    • beg:开始索引,默认为0,闭区间。

    • end:结束索引,开区间,默认为字符串的长度。

  • 实例

    str = 'Hello World'
    
    print(str.index('H', 0, 4))
    print(str.index('0', 0, 5))
     	
     	
    out:
    	0
    	ValueError: substring not found
    

10. str.isalnum()

  • 用途

    检测字符串是否由字母和数字组成。

    如果字符串至少有一个字符并且所有字符只包含字母或数字则返 回 True,否则返回 False。

  • 实例

    print('123'.isalnum())
    print('abc'.isalnum())
    print('123abc'.isalnum())
    print(''.isalnum())
    print('123abc_'.isalnum())
    print('123abc '.isalnum())
     	
     	
    out:
    	True
    	True
    	True
    	False
    	False
    	False
    

11. str.isalpha()

  • 用途

    检测字符串是否只由字母或文字组成。

    如果字符串至少有一个字符并且所有字符只包含字母或中文字则返回 True, 否则返回 False。

  • 实例

    print('abc'.isalpha())
    print('文字'.isalpha())
    print('abc文字'.isalpha())
    print(''.isalpha())
    print('abc123'.isalpha())
     	
     	
    out:
    	True
    	True
    	True
    	False
    	False
    

12. str.isdigit()

  • 用途

    检测字符串是否只由数字组成。

    如果字符串只包含数字则返回 True 否则返回 False。

  • 实例

    print('123'.isdigit())
    print('123abc'.isdigit())
    print(''.isdigit())
    	 	
     	
    out:
    	True
    	False
    	False
    

13. str.islower()

  • 用途

    检测字符串是否由小写字母组成。

    如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False。

  • 实例

    print('abc'.islower())
    print('abc_!123'.islower())
    print('Abc'.islower())
    print(''.islower())
    	 	
     	
    out:
    	True
    	True
    	False
    	False
    

14. str.isnumeric()

  • 用途

    检测字符串是否只由数字组成,数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字。

    指数类似 ² 与分数类似 ½ 也属于数字。

    如果字符串中只包含数字字符,则返回 True,否则返回 False。

  • 实例

    str = "runoob2016"  
    print (str.isnumeric())
    
    str = "23443434"
    print (str.isnumeric())
    
    s = '\u00B23455'  # s = '²3455'
    print(s.isnumeric())
    
    s = '\u00BD'  # s = '½'
    print(s.isnumeric())
    
    a = "\u0030"  # unicode for 0
    print(a.isnumeric())
    
    b = "\u00B2"  # unicode for ²
    print(b.isnumeric())
    
    c = "10km2"
    print(c.isnumeric())
    	 	
     	
    out:
    	False
    	True
    	True
    	True
    	True
    	True
    	False
    

15. str.isspace()

  • 用途

    检测字符串是否只由空白字符组成(空白符包含:空格、制表符(\t)、换行(\n)、回车(\r)等,空字符串不算空白符)。

    如果字符串中只包含空格,则返回 True,否则返回 False。

  • 实例

    print (' \t\r\n'.isspace())
    print(' 12 '.isspace())
    	 	
     	
    out:
    	True
    	False
    

16. str.istitle()

  • 用途

    检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

    如果字符串中所有的单词拼写首字母为大写,且其他字母为小写则返回 True,否则返回 False。

  • 实例

    print ('Hello World'.istitle())
    print('hello World'.istitle())
    print('HelloWorld'.istitle())
    	 	
     	
    out:
    	True
    	False
    	False
    

17. str.isupper()

  • 用途

    检测字符串中所有的字母是否都为大写。

    如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False。

  • 实例

    print('ABC'.isupper())
    print('ABC_!123'.isupper())
    print('Abc'.isupper())
    print(''.isupper())
    	 	
     	
    out:
    	True
    	True
    	False
    	False
    

18. str.join(sequence)

  • 用途

    用于将序列中的元素以指定的字符连接生成一个新的字符串。

  • 参数

    • sequence:要连接的元素序列。
  • 实例

    str = ['a', 'b', 'c', 'd']
    print("-".join(str))
    	 	
     	
    out:
    	a-b-c-d
    

19. len( s )

  • 用途

    返回对象(字符、列表、元组等)长度或项目个数。

  • 参数

    • s:对象。
  • 实例

    str = 'hello world'
    print(len(str))
    
    arr = ['a', 'b', 'c', 'd']
    print(len(arr))
    	 	
     	
    out:
    	11
    	4
    

20. str.ljust(width[, fillchar])

  • 用途

    返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

  • 参数

    • width:指定字符串长度。

    • fillchar:填充字符,默认为空格。

  • 实例

    str = '   hello world'
    print(str.ljust(20, '*'))
    	 	
     	
    out:
    	   hello world******
    

21. str.lower()

  • 用途

    转换字符串中所有大写字符为小写。

  • 实例

    str = 'Hello World 123'
    print(str.lower())
    	 	
     	
    out:
    	hello world 123
    

22. str.lstrip([chars])

  • 用途

    用于截掉字符串左边的空格或指定字符。

  • 参数

    • char:指定截取的字符。
  • 实例

    str = '  hello world  '
    print(str.lstrip())
    
    str = 'xxhello worldxx'
    print(str.lstrip('x'))
    	 	
     	
    out:
    	hello world  
    	hello worldxx
    

23. str.maketrans(intab, outtab)

  • 用途

    用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

    两个字符串的长度必须相同,为一一对应的关系。

    注:Python3.4 已经没有 string.maketrans() 了,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。

  • 参数

    • intab:字符串中要替代的字符组成的字符串。

    • outtab:相应的映射字符的字符串。

  • 实例

    intab = "aeo"
    outtab = "123"
    trantab = str.maketrans(intab, outtab)
    
    str = "hello world"
    print (str.translate(trantab))
    	 	
     	
    out:
    	h2ll3 w3rld
    

24. max(str)

  • 用途

    返回字符串中最大的字母。

    在有大小写的字符串中返回的是小写字母的最大值。

  • 参数

    • str:字符串。
  • 实例

    str = 'aAbBcCdD'
    print(max(str))	
    
    
    out:
    	d
    

25. min(str)

  • 用途

    返回字符串中最小的字母。

  • 参数

    • istr:字符串。
  • 实例

    str = 'aAbBcCdD'
    print(min(str)) 	
    
    
    out:
    	a
    

26. str.replace(old, new[, max])

  • 用途

    把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

  • 参数

    • old:将被替换的子字符串。

    • new:新字符串,用于替换old子字符串。

    • max:可选字符串, 替换不超过 max 次。

  • 实例

    str = 'hello world'
    print(str.replace('o', 'x'))	
    
    
    out:
    	hellx wxrld
    

27. str.rfind(str, beg=0 end=len(string))

  • 用途

    返回字符串最后一次出现的位置,如果没有匹配项则返回-1。

  • 参数

    • str:查找的字符串。

    • beg:开始查找的位置,默认为0,闭区间。

    • end:结束查找位置,开区间,默认为字符串的长度。

  • 实例

    str = 'hello world'
    print(str.replace('o', 'x'))
    print(str.rfind('o'))
    print(str.rfind('o', 0, 4))	
    
    
    out:
    	7
    	-1
    

28. str.rindex(str, beg=0 end=len(string))

  • 用途

    返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常。

  • 参数

    • str:查找的字符串。

    • beg:开始查找的位置,默认为0,闭区间。

    • end:结束查找位置,开区间,默认为字符串的长度。

  • 实例

    str = 'hello world'
    print(str.replace('o', 'x'))
    print(str.rfind('o'))
    print(str.rfind('o', 0, 4))	
    
    
    out:
    	7
    	ValueError: substring not found
    

29. str.rjust(width[, fillchar])

  • 用途

    返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

  • 参数

    • width:指定字符串长度。

    • fillchar:填充字符,默认为空格。

  • 实例

    str = '  hello world'
    print(str.rjust(20, '*'))
    
    
    out:
    	*******  hello world
    

30. str.rstrip([chars])

  • 用途

    删除 string 字符串末尾的指定字符(默认为空格)。

  • 参数

    • char:指定截取的字符。
  • 实例

    str = '  hello world  '
    print(str.rstrip())
    
    str = 'xxhello worldxx'
    print(str.rstrip('x'))
    	 	
     	
    out:
    	  hello world
    	xxhello world
    

31. str.split(str="", num=string.count(str))

  • 用途

    通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。

    返回分割后的字符串列表。

  • 参数

    • str:分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

    • num:分割次数。默认为 -1, 即分隔所有。

  • 实例

    print('he\tllo wor\nld'.split())
    print('hello world'.split('o'))
    print('hello world'.split('o', 1))
    	 	
     	
    out:
    	['he', 'llo', 'wor', 'ld']
    	['hell', ' w', 'rld']
    	['hell', ' world']
    

32. str.splitlines([keepends])

  • 用途

    按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表。

  • 参数

    • keepends:在输出结果里是否去掉换行符(’\r’, ‘\r\n’, \n’),默认为 False,不包含换行符,如果为 True,则保留换行符。
  • 实例

    print('ab c\n\nde fg\rkl\r\n'.splitlines())
    print('ab c\n\nde fg\rkl\r\n'.splitlines(True))	 	
     	
    out:
    	['ab c', '', 'de fg', 'kl']
    	['ab c\n', '\n', 'de fg\r', 'kl\r\n']
    

33. str.startswith(substr,beg=0,end=len(string))

  • 用途

    用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

  • 参数

    • substr:指定的子字符串。

    • beg:可选参数用于设置字符串检测的起始位置,闭区间。

    • end:可选参数用于设置字符串检测的结束位置,开区间。

  • 实例

    print('hello world'.startswith('h'))
    print('hello world'.startswith('e', 1))	 	
     	
    out:
    	True
    	True
    

34. str.strip([chars])

  • 用途

    用于移除字符串头尾指定的字符(默认为空格)或字符序列。

    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

  • 参数

    • chars:移除字符串头尾指定的字符序列,如果不带参数,默认是清除两边的空白符,例如:/n, /r, /t, ’ '。
  • 实例

    # strip() 处理的时候,如果不带参数,默认是清除两边的空白符,例如:/n, /r, /t, ' ')。
    print('  hello world\n'.strip())
    
    # 只要头尾包含有指定字符序列中的字符就删除,并不需要顺序一致
    print('123abc321'.strip('12')) 	 	
     	
     	
    out:
    	hello world
    	3abc3
    

35. str.swapcase()

  • 用途

    用于对字符串的大小写字母进行转换。

    返回大小写字母转换后生成的新字符串。

  • 实例

    print('Hello World'.swapcase())	 	
     	
     	
    out:
    	hELLO wORLD
    

36. str.title()

  • 用途

    根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。

    注意,非字母后的第一个字母将转换为大写字母

  • 实例

    # 所有单词的首字母都转化为大写
    print('hello world'.title())
    
    # 非字母后的第一个字母将转换为大写字母
    print('acb 1d_e f'.title()) 	 	
     	
     	
    out:
    	Hello World
    	Acb 1D_E F
    

37. str.translate(table)、bytes.translate(table[, delete])、bytearray.translate(table[, delete])

  • 用途

    返回"标题化"的字符串,就是说所有单词的首个字母转化为大写,其余字母均为小写(见 istitle())。

    注意,str 类型的 translate() 函数只接受一个参数

  • 参数

    • table:翻译表,翻译表是通过 maketrans() 方法转换而来。

    • deletechars:字符串中要过滤的字符列表。

  • 实例

    table = {'e': '0', 'o': '1', 'd': '2'}  # 映射表中必须全部是字符串
    trantab = str.maketrans(table)  # 制作翻译表
    
    str = 'hello world'
    print(str.translate(trantab)) 	 	
     	
     	
    out:
    	h0ll1 w1rl2
    

38. str.upper()

  • 用途

    将字符串中的小写字母转为大写字母。

  • 实例

    print('abc123'.upper())	 	
     	
     	
    out:
    	ABC123
    

39. str.zfill(width)

  • 用途

    返回指定长度的字符串,原字符串右对齐,前面填充0。

  • 参数

    • width:指定字符串的长度。原字符串右对齐,前面填充0。
  • 实例

    print('hello world'.zfill(10))  # 指定长度小于原字符串长度,返回原字符串
    print('hello world'.zfill(20))	 	
     	
     	
    out:
    	hello world
    	000000000hello world
    

40. str.isdecimal()

  • 用途

    检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。

    如果字符串是否只包含十进制字符返回True,否则返回False。

    注意: python2 中定义一个十进制字符串,只需要在字符串前添加 ‘u’ 前缀即可。

  • 实例

    print('123'.isdecimal())
    print('3.14'.isdecimal())  # 小数不行  
    print('abc123'.isdecimal())	 	
     	
     	
    out:
    	True
    	False
    	False
    

s.isdigit、isdecimal 和 s.isnumeric 区别

  • isdigit()

    True: Unicode数字,byte数字(单字节),全角数字(双字节)

    False: 汉字数字,罗马数字,小数

    Error: 无

  • isdecimal()

    True: Unicode数字,全角数字(双字节)

    False: 罗马数字,汉字数字,小数

    Error: byte数字(单字节)

  • isnumeric()

    True: Unicode 数字,全角数字(双字节),汉字数字

    False: 小数,罗马数字

    Error: byte数字(单字节)

  • 实例

    num = "1"  #unicode
    num.isdigit()   # True
    num.isdecimal()  # True
    num.isnumeric()  # True
    
    num = "1"  # 全角
    num.isdigit()   # True
    num.isdecimal()  # True
    num.isnumeric()  # True
    
    num = b"1"  # byte
    num.isdigit()  # True
    num.isdecimal()  # AttributeError 'bytes' object has no attribute 'isdecimal'
    num.isnumeric()  # AttributeError 'bytes' object has no attribute 'isnumeric'
    
    num = "IV"  # 罗马数字
    num.isdigit()  # False
    num.isdecimal()  # False
    num.isnumeric()  # False
    
    num = "四"  # 汉字
    num.isdigit()  # False
    num.isdecimal()  # False
    num.isnumeric()  # True
    
    num = "3.14"  # 小数
    num.isdigit()  # False
    num.isdecimal()  # False
    num.isnumeric()  # False
    
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值