关于Python3字符串常用方法

    技术2023-05-28  20

    1、字符串方法

    >>> for i in dir(str): ... if not i.startswith('_'): ... print(i) ... capitalize casefold center count encode endswith expandtabs find format format_map index isalnum isalpha isascii isdecimal isdigit isidentifier islower isnumeric isprintable isspace istitle isupper join ljust lower lstrip maketrans partition replace rfind rindex rjust rpartition rsplit rstrip split splitlines startswith strip swapcase title translate upper zfill

    2、字符串方法解析

    初始化一个字符串

    >>> mystr = "hello world, you can do it, and just do yourself." >>> mystr 'hello world, you can do it, and just do yourself.' capitalize 把字符串的第一个字符大写,并不改变原来的字符串 >>> mystr.capitalize() 'Hello world, you can do it, and just do yourself.'

    casefold 效果和lower()相似,将大写字符转为小写。区别是:lower()只对ASCII编码有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold()

    center 字符串排版方法,可参照rjust、ljust

    >>> 'hello'.center(100) ' hello ' >>> 'hello'.center(100, '*') '***********************************************hello************************************************' count 计算字符串子集的个数,S.count(sub[, start[, end]]) -> int >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.count('you') 2 encode 为字符串编码 >>> mystr.encode('utf-8') b'hello world, you can do it, and just do yourself.' >>> mystr.encode('utf-8').decode('utf-8') 'hello world, you can do it, and just do yourself.' endswith 判断字符串是否以指定字符串结尾,S.endswith(suffix[, start[, end]]) -> bool >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.endswith('yourself.') True >>> mystr[10:30] 'd, you can do it, an' >>> mystr.endswith('an', 10, 30) # 指定位置以字符串后缀结尾 True expandtabs 把字符串中的 tab 符号(’\t’)转为空格,expandtabs(self, /, tabsize=8),tab 符号(’\t’)默认的空格数是 8。 >>> 'hello world\tdone'.expandtabs() 'hello world done' find 检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.find('do') 21 >>> mystr.find('dod') -1 format 字符串格式化输出 >>> 'hello {name}'.format(name='xiaoming') 'hello xiaoming' format_map 字符串格式化输出,用于字典关系映射 >>> student = {'name': 'xiaoming', 'age':28} >>> 'Hello guys, my name is {name} and I am {age} years old.'.format(name='xx', age=29) 'Hello guys, my name is xx and I am 29 years old.' >>> 'Hello guys, my name is {name} and I am {age} years old.'.format_map(student) 'Hello guys, my name is xiaoming and I am 28 years old.' index 用于获取字符串的索引值,如果不存在就抛出一个异常,可以指定范围 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.index('world') 6 >>> mystr.index('word') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found isalnum 判断是否是alnum >>> 'hello123'.isalnum() True isalpha 判断是否是alpha >>> 'hello'.isalpha() True isascii 判断是否是ascii >>> 'a'.isascii() True >>> 'aA'.isascii() True isdecimal 判断是否是decimal >>> '11'.isdecimal() True isdigit 判断是否是数字 >>> '11'.isdigit() True isidentifier 判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法 >>> '1_name'.isidentifier() False >>> 'name'.isidentifier() True >>> 'name_1'.isidentifier() True islower 判断字符串是否全小写 >>> 'Hello World'.lower().islower() True >>> 'Hello World'.islower() False >>> 'Hello World'.lower().islower() True >>> 'hello world'.islower() True isnumeric 判断是否是数字 >>> '1'.isnumeric() True >>> '1ds12121'.isnumeric() False isprintable 判断是否是可打印字符 >>> 'hello'.isprintable() True isspace 判断是否是空格 >>> ''.isspace() False >>> ' '.isspace() True istitle 判断是否是title格式,一般就是首字母大写这种格式 >>> 'Hello World'.istitle() True >>> 'HEllo World'.istitle() False >>> 'hello World'.istitle() False isupper 判断是否大写 >>> 'Hello World'.isupper() False join 连接两个或多个字符串,在处理长度较长的字符串时join方法比“+”效率更高 >>> '.'.join(['www', 'baidu', 'com']) 'www.baidu.com' >>> >>> '-'.join(['www', 'baidu', 'com']) 'www-baidu-com' ljust 字符串的排版方法,它将原字符串左对齐,使用空格填充至指定长度,并返回新的字符串。如果指定的长度小于原字符串长度,则直接将字符串返回。 str.ljust(width, fill_character):width字符串宽度、fill_character填充字符串,必须是字符类型或者是长度为1的字符串,否则Python报错TypeError >>> 'hello'.ljust(50, ' ') 'hello ' lower 将大写字母转换成小写 >>> 'Hello World'.lower() 'hello world' lstrip 删除字符串左边的空格 >>> ' hello '.lstrip() 'hello ' maketrans 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。 >>> intab = "aeiou" >>> outtab = "12345" >>> trantab = str.maketrans(intab, outtab) >>> "this is string example....wow!!!".translate(trantab) 'th3s 3s str3ng 2x1mpl2....w4w!!!' # a=>1, e=>2, ...... partition 根据指定的分隔符将字符串进行分割,如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.partition(',') ('hello world', ',', ' you can do it, and just do yourself.') replace 把字符串中的 old(旧字符串) 替换成 new(新字符串),返回一个新字符串,replace(old, new[, max]) 如果指定第三个参数max,则替换不超过 max 次。 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.replace('you', 'we', 1) 'hello world, we can do it, and just do yourself.' >>> mystr 'hello world, you can do it, and just do yourself.' rfind 返回字符串最后一次出现的位置,如果没有匹配项则返回-1 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.rfind('do') 37 >>> mystr.rfind('dod') -1 rindex 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.rindex('do') 37 >>> mystr[37] 'd' rjust 字符串的排版方法,它将原字符串右对齐,使用空格填充至指定长度,并返回新的字符串。如果指定的长度小于原字符串长度,则直接将字符串返回。 str.rjust(width, fill_character):width字符串宽度、fill_character填充字符串,必须是字符类型或者是长度为1的字符串,否则Python报错TypeError >>> 'hello'.rjust(50, '*') '*********************************************hello' rpartition 从目标字符串的末尾开始搜索分割符,如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.rpartition(',') ('hello world, you can do it', ',', ' and just do yourself.') rsplit 从右侧开始将字符串拆分为列表 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.rsplit() ['hello', 'world,', 'you', 'can', 'do', 'it,', 'and', 'just', 'do', 'yourself.'] >>> mystr.rsplit(',', 1) ['hello world, you can do it', ' and just do yourself.'] rstrip 删除字符串右边的空格. >>> ' hello '.rstrip() ' hello' >>> >>> 'hello'.ljust(50, '*').rjust(100, '*') '**************************************************hello*********************************************' split 指定分隔符对字符串进行分片,split(self, /, sep=None, maxsplit=-1)如果设置了maxsplit表示分隔字符串的个数:N+1 >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.split() # 默认以空格分隔 ['hello', 'world,', 'you', 'can', 'do', 'it,', 'and', 'just', 'do', 'yourself.'] >>> mystr.split(maxsplit=2) # 以空格作为分隔符,分成3个字符 ['hello', 'world,', 'you can do it, and just do yourself.'] >>> mystr.split(',') # 设置分隔符为“,” ['hello world', ' you can do it', ' and just do yourself.'] splitlines 按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 Unix系统里,每行结尾只有“<换行>”,即"\n"; Windows系统里面,每行结尾是“<回车><换行>”,即“\r\n”; Mac系统里,每行结尾是“<回车>”,即"\r"; >>> str1 = 'ab c\n\nde fg\rkl\r\n' >>> str1.splitlines() ['ab c', '', 'de fg', 'kl'] >>> str1.splitlines(True) ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] >>> startswith :判断字符串是否以指定字符串前缀开头,S.startswith(prefix[, start[, end]]) -> bool >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr.startswith('hello') True >>> >>> mystr 'hello world, you can do it, and just do yourself.' >>> mystr[13:40] 'you can do it, and just do ' >>> mystr.startswith('you', 13, 40) # 从指定位置开始,以‘you’开头 True strip 删除字符串两边的空格 >>> ' hello '.strip() 'hello' swapcase 大写字母变小写,小写变大写 >>> 'Hello World'.swapcase() 'hELLO wORLD' title 将字符串改变为title格式,一般是单词的首字母大写 >>> 'hello world'.title() 'Hello World'

    translate 跟据maketrans制作的映射表,将字符串翻译出来 参照maketrans

    upper 小写字母为大写

    >>> mystr.upper() 'HELLO WORLD, YOU CAN DO IT, AND JUST DO YOURSELF.' zfill 返回指定长度的字符串,原字符串右对齐,前面填充0 >>> 'hello world'.zfill(50) '000000000000000000000000000000000000000hello world' >>> 'hello world'.rjust(50, '0') '000000000000000000000000000000000000000hello world'
    Processed: 0.023, SQL: 8