Python 的内置字符串方法(收藏专用)

4.7k 次阅读  ·  读完需要 44 分钟

5

字符串处理是非常常用的技能,但 Python 内置字符串方法太多,常常遗忘,为了便于快速参考,特地依据 Python 3.5.1 给每个内置方法写了示例并进行了归类,便于大家索引。
PS: 可以点击概览内的绿色标题进入相应分类或者通过右侧边栏文章目录快速索引相应方法。

概览

字符串大小写转换

  • str.capitalize()
  • str.lower()
  • str.casefold()
  • str.swapcase()
  • str.title()
  • str.upper()

字符串格式输出

  • str.center(width[, fillchar])
  • str.ljust(width[, fillchar]); str.rjust(width[, fillchar])
  • str.zfill(width)
  • str.expandtabs(tabsize=8)
  • str.format(^args, ^^kwargs)
  • str.format_map(mapping)

字符串搜索定位与替换

  • str.count(sub[, start[, end]])
  • str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]])
  • str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]])
  • str.replace(old, new[, count])
  • str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])
  • static str.maketrans(x[, y[, z]]); str.translate(table)

字符串的联合与分割

  • str.join(iterable)
  • str.partition(sep); str.rpartition(sep)
  • str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)
  • str.splitlines([keepends])

字符串条件判断

  • str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])
  • str.isalnum()
  • str.isalpha()
  • str.isdecimal(); str.isdigit(); str.isnumeric()
  • str.isidentifier()
  • str.islower()
  • str.isprintable()
  • str.isspace()
  • str.istitle()
  • str.isupper()

字符串编码

  • str.encode(encoding="utf-8", errors="strict")

大小写转换

str.capitalize()

将首字母转换成大写,需要注意的是如果首字没有大写形式,则返回原字符串。

‘adi dog‘.capitalize()
# ‘Adi dog‘

‘abcd 徐‘.capitalize()
# ‘Abcd 徐‘

‘徐 abcd‘.capitalize()
# ‘徐 abcd‘

‘?‘.capitalize()
# ‘SS‘

str.lower()

将字符串转换成小写,其仅对 ASCII 编码的字母有效。

‘DOBI‘.lower()
# ‘dobi‘

‘?‘.lower()   # ‘?‘ 为德语小写字母,其有另一种小写 ‘ss‘, lower 方法无法转换
# ‘?‘

‘徐 ABCD‘.lower()
# ‘徐 abcd‘

str.casefold()

将字符串转换成小写,Unicode 编码中凡是有对应的小写形式的,都会转换。

‘DOBI‘.casefold()
# ‘dobi‘

‘?‘.casefold()   #德语中小写字母 ? 等同于小写字母 ss, 其大写为 SS
# ‘ss‘

str.swapcase()

对字符串字母的大小写进行反转。

‘徐Dobi a123 ?‘.swapcase()
#: ‘徐dOBI A123 SS‘    这里的 ? 被转成 SS 是一种大写

但需要注意的是 s.swapcase().swapcase() == s 不一定为真:

u‘\xb5‘
# ‘μ‘

u‘\xb5‘.swapcase()
# ‘Μ‘

u‘\xb5‘.swapcase().swapcase()
# ‘μ‘

hex(ord(u‘\xb5‘.swapcase().swapcase()))
Out[154]: ‘0x3bc‘

这里 ‘Μ‘(是 mu 不是 M) 的小写正好与 ‘μ‘ 的写法一致。

str.title()

将字符串中每个“单词”首字母大写。其判断“单词”的依据则是基于空格和标点,所以应对英文撇好所有格或一些英文大写的简写时,会出错。

‘Hello world‘.title()
# ‘Hello World‘

‘中文abc def 12gh‘.title()
# ‘中文Abc Def 12Gh‘

# 但这个方法并不完美:
"they‘re bill‘s friends from the UK".title()
# "They‘Re Bill‘S Friends From The Uk"

str.upper()

将字符串所有字母变为大写,会自动忽略不可转成大写的字符。

‘中文abc def 12gh‘.upper()
# ‘中文ABC DEF 12GH‘

需要注意的是 s.upper().isupper() 不一定为 True

字符串格式输出

str.center(width[, fillchar])

将字符串按照给定的宽度居中显示,可以给定特定的字符填充多余的长度,如果指定的长度小于字符串长度,则返回原字符串。

‘12345‘.center(10, ‘*‘)
# ‘**12345***‘

‘12345‘.center(10)
# ‘  12345   ‘

str.ljust(width[, fillchar]); str.rjust(width[, fillchar])

返回指定长度的字符串,字符串内容居左(右)如果长度小于字符串长度,则返回原始字符串,默认填充为 ASCII 空格,可指定填充的字符串。

‘dobi‘.ljust(10)
# ‘dobi      ‘

‘dobi‘.ljust(10, ‘~‘)
# ‘dobi~~~~~~‘

‘dobi‘.ljust(3, ‘~‘)
# ‘dobi‘

‘dobi‘.ljust(3)
# ‘dobi‘

str.zfill(width)

用 ‘0‘ 填充字符串,并返回指定宽度的字符串。

"42".zfill(5)
# ‘00042‘
"-42".zfill(5)
# ‘-0042‘

‘dd‘.zfill(5)
# ‘000dd‘

‘--‘.zfill(5)
# ‘-000-‘

‘ ‘.zfill(5)
# ‘0000 ‘

‘‘.zfill(5)
# ‘00000‘

‘dddddddd‘.zfill(5)
# ‘dddddddd‘

str.expandtabs(tabsize=8)

用指定的空格替代横向制表符,使得相邻字符串之间的间距保持在指定的空格数以内。

tab = ‘1\t23\t456\t7890\t1112131415\t161718192021‘

tab.expandtabs()
# ‘1       23      456     7890    1112131415      161718192021‘
# ‘123456781234567812345678123456781234567812345678‘  注意空格的计数与上面输出位置的关系

tab.expandtabs(4)
# ‘1   23  456 7890    1112131415  161718192021‘
# ‘12341234123412341234123412341234‘  

str.format(^args, ^^kwargs)

格式化字符串的语法比较繁多,官方文档已经有比较详细的 examples,这里就不写例子了,想了解的童鞋可以直接戳这里 Format examples.

str.format_map(mapping)

类似 str.format(*args, **kwargs) ,不同的是 mapping 是一个字典对象。

People = {‘name‘:‘john‘, ‘age‘:56}

‘My name is {name},i am {age} old‘.format_map(People)
# ‘My name is john,i am 56 old‘

字符串搜索定位与替换

str.count(sub[, start[, end]])

text = ‘outer protective covering‘

text.count(‘e‘)
# 4

text.count(‘e‘, 5, 11)
# 1

text.count(‘e‘, 5, 10)
# 0

str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]])

text = ‘outer protective covering‘

text.find(‘er‘)
# 3

text.find(‘to‘)
# -1

text.find(‘er‘, 3)
Out[121]: 3

text.find(‘er‘, 4)
Out[122]: 20

text.find(‘er‘, 4, 21)
Out[123]: -1

text.find(‘er‘, 4, 22)
Out[124]: 20

text.rfind(‘er‘)
Out[125]: 20

text.rfind(‘er‘, 20)
Out[126]: 20

text.rfind(‘er‘, 20, 21)
Out[129]: -1

str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]])

与 find() rfind() 类似,不同的是如果找不到,就会引发 ValueError

str.replace(old, new[, count])

‘dog wow wow jiao‘.replace(‘wow‘, ‘wang‘)
# ‘dog wang wang jiao‘

‘dog wow wow jiao‘.replace(‘wow‘, ‘wang‘, 1)
# ‘dog wang wow jiao‘

‘dog wow wow jiao‘.replace(‘wow‘, ‘wang‘, 0)
# ‘dog wow wow jiao‘

‘dog wow wow jiao‘.replace(‘wow‘, ‘wang‘, 2)
# ‘dog wang wang jiao‘

‘dog wow wow jiao‘.replace(‘wow‘, ‘wang‘, 3)
# ‘dog wang wang jiao‘

str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])

‘  dobi‘.lstrip()
# ‘dobi‘
‘db.kun.ac.cn‘.lstrip(‘dbk‘)
# ‘.kun.ac.cn‘

‘ dobi   ‘.rstrip()
# ‘ dobi‘
‘db.kun.ac.cn‘.rstrip(‘acn‘)
# ‘db.kun.ac.‘

‘   dobi   ‘.strip()
# ‘dobi‘
‘db.kun.ac.cn‘.strip(‘db.c‘)
# ‘kun.ac.cn‘
‘db.kun.ac.cn‘.strip(‘cbd.un‘)
# ‘kun.a‘

static str.maketrans(x[, y[, z]]); str.translate(table)

maktrans 是一个静态方法,用于生成一个对照表,以供 translate 使用。
如果 maktrans 仅一个参数,则该参数必须是一个字典,字典的 key 要么是一个 Unicode 编码(一个整数),要么是一个长度为 1 的字符串,字典的 value 则可以是任意字符串、None或者 Unicode 编码。

a = ‘dobi‘
ord(‘o‘)
# 111

ord(‘a‘)
# 97

hex(ord(‘狗‘))
# ‘0x72d7‘

b = {‘d‘:‘dobi‘, 111:‘ is ‘, ‘b‘:97, ‘i‘:‘\u72d7\u72d7‘}
table = str.maketrans(b)

a.translate(table)
# ‘dobi is a狗狗‘

如果 maktrans 有两个参数,则两个参数形成映射,且两个字符串必须是长度相等;如果有第三个参数,则第三个参数也必须是字符串,该字符串将自动映射到 None

a = ‘dobi is a dog‘

table = str.maketrans(‘dobi‘, ‘alph‘)

a.translate(table)
# ‘alph hs a alg‘

table = str.maketrans(‘dobi‘, ‘alph‘, ‘o‘)

a.translate(table)
# ‘aph hs a ag‘

字符串的联合与分割

str.join(iterable)

用指定的字符串,连接元素为字符串的可迭代对象。

‘-‘.join([‘2012‘, ‘3‘, ‘12‘])
# ‘2012-3-12‘

‘-‘.join([2012, 3, 12])
# TypeError: sequence item 0: expected str instance, int found

‘-‘.join([‘2012‘, ‘3‘, b‘12‘])  #bytes 为非字符串
# TypeError: sequence item 2: expected str instance, bytes found

‘-‘.join([‘2012‘])
# ‘2012‘

‘-‘.join([])
# ‘‘

‘-‘.join([None])
# TypeError: sequence item 0: expected str instance, NoneType found

‘-‘.join([‘‘])
# ‘‘

‘,‘.join({‘dobi‘:‘dog‘, ‘polly‘:‘bird‘})
# ‘dobi,polly‘

‘,‘.join({‘dobi‘:‘dog‘, ‘polly‘:‘bird‘}.values())
# ‘dog,bird‘

str.partition(sep); str.rpartition(sep)

‘dog wow wow jiao‘.partition(‘wow‘)
# (‘dog ‘, ‘wow‘, ‘ wow jiao‘)

‘dog wow wow jiao‘.partition(‘dog‘)
# (‘‘, ‘dog‘, ‘ wow wow jiao‘)

‘dog wow wow jiao‘.partition(‘jiao‘)
# (‘dog wow wow ‘, ‘jiao‘, ‘‘)

‘dog wow wow jiao‘.partition(‘ww‘)
# (‘dog wow wow jiao‘, ‘‘, ‘‘)

‘dog wow wow jiao‘.rpartition(‘wow‘)
Out[131]: (‘dog wow ‘, ‘wow‘, ‘ jiao‘)

‘dog wow wow jiao‘.rpartition(‘dog‘)
Out[132]: (‘‘, ‘dog‘, ‘ wow wow jiao‘)

‘dog wow wow jiao‘.rpartition(‘jiao‘)
Out[133]: (‘dog wow wow ‘, ‘jiao‘, ‘‘)

‘dog wow wow jiao‘.rpartition(‘ww‘)
Out[135]: (‘‘, ‘‘, ‘dog wow wow jiao‘)

str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)

‘1,2,3‘.split(‘,‘), ‘1, 2, 3‘.rsplit()
# ([‘1‘, ‘2‘, ‘3‘], [‘1,‘, ‘2,‘, ‘3‘])

‘1,2,3‘.split(‘,‘, maxsplit=1),  ‘1,2,3‘.rsplit(‘,‘, maxsplit=1)
# ([‘1‘, ‘2,3‘], [‘1,2‘, ‘3‘])

‘1 2 3‘.split(), ‘1 2 3‘.rsplit()
# ([‘1‘, ‘2‘, ‘3‘], [‘1‘, ‘2‘, ‘3‘])

‘1 2 3‘.split(maxsplit=1), ‘1 2 3‘.rsplit(maxsplit=1)
# ([‘1‘, ‘2 3‘], [‘1 2‘, ‘3‘])

‘   1   2   3   ‘.split()
# [‘1‘, ‘2‘, ‘3‘]

‘1,2,,3,‘.split(‘,‘), ‘1,2,,3,‘.rsplit(‘,‘)
# ([‘1‘, ‘2‘, ‘‘, ‘3‘, ‘‘], [‘1‘, ‘2‘, ‘‘, ‘3‘, ‘‘])

‘‘.split()
# []
‘‘.split(‘a‘)
# [‘‘]
‘bcd‘.split(‘a‘)
# [‘bcd‘]
‘bcd‘.split(None)
# [‘bcd‘]

str.splitlines([keepends])

字符串以行界符为分隔符拆分为列表;当 keepends 为True,拆分后保留行界符,能被识别的行界符见官方文档

‘ab c\n\nde fg\rkl\r\n‘.splitlines()
# [‘ab c‘, ‘‘, ‘de fg‘, ‘kl‘]
‘ab c\n\nde fg\rkl\r\n‘.splitlines(keepends=True)
# [‘ab c\n‘, ‘\n‘, ‘de fg\r‘, ‘kl\r\n‘]

"".splitlines(), ‘‘.split(‘\n‘)      #注意两者的区别
# ([], [‘‘])
"One line\n".splitlines()
# ([‘One line‘], [‘Two lines‘, ‘‘])

字符串条件判断

str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])

text = ‘outer protective covering‘

text.endswith(‘ing‘)
# True

text.endswith((‘gin‘, ‘ing‘))
# True
text.endswith(‘ter‘, 2, 5)
# True

text.endswith(‘ter‘, 2, 4)
# False

str.isalnum()

字符串和数字的任意组合,即为真,简而言之:

只要 c.isalpha()c.isdecimal()c.isdigit()c.isnumeric() 中任意一个为真,则 c.isalnum() 为真。

‘dobi‘.isalnum()
# True

‘dobi123‘.isalnum()
# True

‘123‘.isalnum()
# True

‘徐‘.isalnum()
# True

‘dobi_123‘.isalnum()
# False

‘dobi 123‘.isalnum()
# False

‘%‘.isalnum()
# False

str.isalpha()

Unicode 字符数据库中作为 “Letter”(这些字符一般具有 “Lm”, “Lt”, “Lu”, “Ll”, or “Lo” 等标识,不同于 Alphabetic) 的,均为真。

‘dobi‘.isalpha()
# True

‘do bi‘.isalpha()
# False

‘dobi123‘.isalpha()
# False

‘徐‘.isalpha()
# True

str.isdecimal(); str.isdigit(); str.isnumeric()

三个方法的区别在于对 Unicode 通用标识的真值判断范围不同:

isdecimal: Nd,
isdigit: No, Nd,
isnumeric: No, Nd, Nl

digit 与 decimal 的区别在于有些数值字符串,是 digit 却非 decimal ,具体戳 这里

num = ‘\u2155‘
print(num)
# ?
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)

num = ‘\u00B2‘
print(num)
# 2
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, True, True)

num = "1"  #unicode
num.isdecimal(), num.isdigit(), num.isnumeric()
# (Ture, True, True)

num = "‘Ⅶ‘"
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)

num = "十"
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, 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‘

str.isidentifier()

判断字符串是否可为合法的标识符。

‘def‘.isidentifier()
# True

‘with‘.isidentifier()
# True

‘false‘.isidentifier()
# True

‘dobi_123‘.isidentifier()
# True

‘dobi 123‘.isidentifier()
# False

‘123‘.isidentifier()
# False

str.islower()

‘徐‘.islower()
# False

‘?‘.islower()   #德语大写字母
# False

‘a徐‘.islower()
# True

‘ss‘.islower()
# True

‘23‘.islower()
# False

‘Ab‘.islower()
# False

str.isprintable()

判断字符串的所有字符都是可打印字符或字符串为空。Unicode 字符集中 “Other” “Separator” 类别的字符为不可打印的字符(但不包括 ASCII 的空格(0x20))。

‘dobi123‘.isprintable()
# True

‘dobi123\n‘.isprintable()
Out[24]: False

‘dobi 123‘.isprintable()
# True

‘dobi.123‘.isprintable()
# True

‘‘.isprintable()
# True

str.isspace()

判断字符串中是否至少有一个字符,并且所有字符都是空白字符。

In [29]: ‘\r\n\t‘.isspace()
Out[29]: True

In [30]: ‘‘.isspace()
Out[30]: False

In [31]: ‘ ‘.isspace()
Out[31]: True

str.istitle()

判断字符串中的字符是否是首字母大写,其会忽视非字母字符。

‘How Python Works‘.istitle()
# True

‘How Python WORKS‘.istitle()
# False

‘how python works‘.istitle()
# False

‘How Python  Works‘.istitle()
# True

‘ ‘.istitle()
# False

‘‘.istitle()
# False

‘A‘.istitle()
# True

‘a‘.istitle()
# False

‘甩甩Abc Def 123‘.istitle()
# True

str.isupper()

‘徐‘.isupper()
# False

‘DOBI‘.isupper()
Out[41]: True

‘Dobi‘.isupper()
# False

‘DOBI123‘.isupper()
# True

‘DOBI 123‘.isupper()
# True

‘DOBI\t 123‘.isupper()
# True

‘DOBI_123‘.isupper()
# True

‘_123‘.isupper()
# False

字符串编码

str.encode(encoding="utf-8", errors="strict")

fname = ‘徐‘

fname.encode(‘ascii‘)
# UnicodeEncodeError: ‘ascii‘ codec can‘t encode character ‘\u5f90‘...

fname.encode(‘ascii‘, ‘replace‘)
# b‘?‘

fname.encode(‘ascii‘, ‘ignore‘)
# b‘‘

fname.encode(‘ascii‘, ‘xmlcharrefreplace‘)
# b‘徐‘

fname.encode(‘ascii‘, ‘backslashreplace‘)
# b‘\\u5f90‘

参考资料

Python 内置类型字符串方法

原文地址:https://www.cnblogs.com/pscc/p/9569204.html

时间: 2024-08-02 20:17:38

Python 的内置字符串方法(收藏专用)的相关文章

Python字典内置函数&方法

字典内置函数&方法 Python字典包含了以下内置函数: 序号 函数及描述 1 cmp(dict1, dict2)比较两个字典元素. 2 len(dict)计算字典元素个数,即键的总数. 3 str(dict)输出字典可打印的字符串表示. 4 type(variable)返回输入的变量类型,如果变量是字典就返回字典类型. Python字典包含了以下内置函数: 序号 函数及描述 1 radiansdict.clear()删除字典内所有元素 2 radiansdict.copy()返回一个字典的浅复

python的内置排序方法+文件操作

li = [22,34,2,11] print (li) li.sort() print (li) 或者直接 new = sorted(li) print (new) 字符串和数字不能放在一起排序,全是数字按照数字大小排序.如果是字符串,分三类,数字优先于字母优先于中文,字符码排序,从前往后拍,最大位要是小就放在前面,如果相同比下面的一位. 文件操作: 一,打开文件 二,操作文件 三,关闭文件 open(文件名,模式,编码) 我创建了一个'ha.log'文件 f = open('ha.log')

Python的内置方法,abs,all,any,basestring,bin,bool,bytearray,callable,chr,cmp,complex,divmod

Python的内置方法 abs(X):返回一个数的绝对值,X可以是一个整数,长整型,或者浮点数,如果X是一个复数,此方法返回此复数的绝对值(此复数与它的共轭复数的乘积的平方根) >>> abs(3+2j) 3.605551275463989 >>> abs(3-2j) 3.605551275463989 all(iterable):如果迭代器的所有元素都是true,或者空迭代器,则此方法返回true. any(iterable):迭代器只要有一个元素为false,或者空

Python pandas 数据框的str列内置的方法详解

原文链接:http://www.datastudy.cc/to/31 在使用pandas框架的DataFrame的过程中,如果需要处理一些字符串的特性,例如判断某列是否包含一些关键字,某列的字符长度是否小于3等等这种需求,如果掌握str列内置的方法,处理起来会方便很多. 下面我们来详细了解一下,Series类的str自带的方法有哪些. 1.cat() 拼接字符串 例子: >>> Series(['a', 'b', 'c']).str.cat(['A', 'B', 'C'], sep=',

字符串内置基本方法

#一:基本使用# 1 用途: 描述性质的数据,比如人的名字,单个爱好,地址## 2 定义方式# name='egon' #name=str('egon')# x=str(1)# y=str(1.1)# z=str([1,2,3])# n=str({'a':1})# print(type(x))# print(type(y))# print(type(z))# print(type(n)) # 3 常用操作+内置的方法#优先掌握的操作(*****):#1.按索引取值(正向取+反向取) :只能取ms

装饰器、生成器、迭代器、及python中内置函数的使用

一. 装饰器 1. 装饰器的概述 (1)概述:装饰器本质就是函数,主要用来装饰其他函数,为其他函数添加附加功能. (2)使用装饰器的原则 1)不能修改被装饰的函数的源代码 2)不能修改被装饰的函数的调用方式 (3)装饰器原理:函数即"变量".高阶函数.嵌套函数 2.使用装饰器的原因 (1)传统的多个函数模块修改需要同时修改多个函数.如果函数过多,则修改不方便. 如下,如果想要在每个函数中开头结尾分别输入内容,则需要在每个函数开头结尾加入需要输出的内容. def f1():     pr

Python 常用内置函数

abs 取绝对值 print(abs(-1)) #结果1 all(...) all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. 如果iterable的所有元素不为0.''.False或者iterable为空,all(iterable)返回True,否则返回False:函数等价于: 1 def all

3.24 python 常用内置对象 : 运算符、表达式、内置对象(没完待续)

---恢复内容开始--- 对象类型 类型名称 示例 简要说明 数字 int,float,complex 1234,3.14,1.3e5,3+4j 数字大小没有限制 字符串 str 'swd',"I'am a student",'''Python''' 使用单引号.双引号.三引号作为定界符 字节符 bytes b‘hello world’ 以字母b引导,可以使用单.双.三引号作为定界符 列表 list [1,2,3],['b','a',1,2,3] 所有元素放在一对方括号中,元素之间使用

Python-部份内置属性方法

@property类的静态属性,封装内部具体实现细节,调用的时候类似调用数据属性.既可以访问类属性,也可以访问实例属性 ![](https://s1.51cto.com/images/blog/201906/08/6de11e5b657bbb1c6e02f4ed64821fa7.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,ty