测试开发技术网站
博客
设计
设计
开发
Python
测试
unittest
运维
Linux基础应用
CI/CD
CI/CD
数据库
数据库
云计算
云计算
云原生
云原生
爬虫
爬虫
数据分析
数据分析
人工智能
人工智能
登录
注册
Python字符串及其常用方法
收藏本文
作者:redrose2100 类别: 日期:2022-05-04 07:32:33 阅读:892 次 消耗积分:0 分
[TOC] # 1 字符串的表示方法 * (1)字符串可以使用单引号,双引号,三个单引号,单个双引号表示 ```python >>> "hello world" 'hello world' >>> 'hello world' 'hello world' >>> """hello world ... hello world ... hello world ... """ 'hello world\nhello world\nhello world\n' >>> '''hello world ... hello world ... hello world ... ''' 'hello world\nhello world\nhello world\n' ``` * (2)字符串中若有双引号,可以采用单引号嵌套双引号的方式,也可以采用后面要讲的转义的部分 ```python >>> 'he said:"hello world"' 'he said:"hello world"' ``` # 2 转义字符 * (1)常用的转义字符 ```python \n 换行 \\ \ \t 制表符 \" " \' ' ``` * (2)字符串中使用转义举例 ```python >>> print("hello \\n world") hello \n world >>> print("hello \"Tom\"") hello "Tom" >>> print("hello\tworld") hello world >>> print("hello\nworld") hello world ``` * (3)在Windows操作系统上使用文件路径时要特别小心,注意使用转义符对\进行转义 ```python >>> print("C:\north\nrothwest") C: orth rothwest >>> print("C:\\north\\northwest") C:\north\northwest >>> print(r"C:\north\northwest") C:\north\northwest >>> ``` # 3 字符串的常用运算 * (1)字符串可以用加号来拼接字符串,使用*号来重复字符串 ```python >>> "hello" "world" 'helloworld' >>> "hello"*3 'hellohellohello' ``` * (2)字符串可以通过下标获取具体的字符,下标从0开始,下标不允许超过边界 ```python >>> a="hello world" >>> print(a[0]) h >>> print(a[2]) l >>> print(a[-1]) d >>> print(a[-3]) r >>> print(a[11]) Traceback (most recent call last): File "
", line 1, in
IndexError: string index out of range ``` * (3)字符串可以通过切片获取字符串的片段,坚持前闭后开的原则 ```python >>> a="hello world" >>> print(a[0:4]) hell >>> print(a[1:3]) el >>> print(a[0:-1]) hello worl >>> print(a[0:10]) hello worl ``` * (4)字符串中切片操作,右边界值允许炒作最大值,超过后表示取到最右边的字符 ```python >>> print(a[0:11]) hello world ``` * (5)字符串切片操作可以使用三个参数,第三个参数表示步长 ```python >>> print(a[1:9:3]) eoo ``` * (6)字符串切片操作的参数可以省略,省略第一个参数表示左侧从头开始取,省略第二参数,表示右侧到字符串末尾 ```python >>> print(a[:3]) hel >>> print(a[3:]) lo world >>> print(a[::3]) hlwl ``` * (7)字符串切片操作的参数中若第一个参数大于等于第二个参数,且第二个参数不为负数时,表示取出来的子串为空串 ```python >>> print(a[5:1]) >>> print(a[10:0]) ``` * (8)字符串可以通过in或者not in判断字符或者字符串是否在字符串中 ```python >>> 'h' in "hello world" True >>> 'z' in "hello world" False >>> 'z' not in "hello world" True ``` * (9)通过len函数计算字符串的长度 ```python >>> len("hello world") 11 ``` * (10)通过max和min计算字符串中的最小和最大的值 ```python >>> max("hello world") 'w' >>> min("hello world") ' ' ``` * (11)ord可以将字符转换为整数,chr可以将整数转换为字符 ```python >>> ord('a') 97 >>> chr(90) 'Z' ``` # 4 字符串常用的函数 * (1)capitalize() 将字符串首字母大写,其他字母变成小写 ```python >>> a="hello Word HeLLO WORd" >>> a.capitalize() 'Hello word hello word' ``` * (2)lower() 将大写字母转换为小写字母(仅限ASCII编码范围内的语言) ```python >>> a="HEllo WorLD HelLO WoRLD" >>> a.lower() 'hello world hello world' ``` * (3)casefold() 将大写字母转换为小写字母(ASCII编码范围外的语言也支持) ```python >>> a="HEllo WorLD HelLO WoRLD" >>> a.casefold() 'hello world hello world' >>> a="ß" # 德语 >>> a 'ß' >>> a.casefold() 'ss' >>> a.lower() 'ß' ``` * (4)upper() 将小写字母转换为大写字母(仅限ASCII编码范围内的语言) ```python >>> a="hello Word HeLLO WORd" >>> a.upper() 'HELLO WORD HELLO WORD' ``` * (5)swapcase() 将小写字母转换为大写字母,将原来大写的变为小写字母 ```python >>> a="HEllo WorLD HelLO WoRLD" >>> a.swapcase() 'heLLO wORld hELlo wOrld' ``` * (6)title() 将字符串中每个单词的首字母大写 ```python >>> a="HEllo WorLD HelLO WoRLD" >>> a.title() 'Hello World Hello World' ``` * (7)strip(chars=None) 如果chars不填,则去除字符串两端的空格,如果chars指定了字符,则去除字符串两端的chars指定的字符 ```python >>> a=" hello world " >>> a.strip() 'hello world' >>> a="hahahahello world hello world hahahaha" >>> a.strip("ha") 'ello world hello world ' >>> a="hahahahaahello world hahahaha" >>> a.strip("ha") 'ello world ' >>> a="hello world gogole world hello" >>> a.strip("olhe") ' world gogole world ' ``` * (8)lstrip(chars=None),和strip功能类似,只不过lstrip只去除字符串左边空格或者chars指定的字符 ```python >>> a=" hello world " >>> a.lstrip() 'hello world ' >>> a="hello world hello" >>> a.lstrip("elho") ' world hello' ``` * (9)rstrip(chars=None),和strip功能类似,只不过rstrip只去除字符串右边空格或者chars指定的字符 ```python >>> a=" hello world " >>> a.rstrip() ' hello world' >>> a="hello world hello" >>> a.rstrip("elho") 'hello world ' ``` * (10)rjust(width,fillchar=' '),返回一个原字符串右对齐,并使用fillchar指定的字符填充至width长度的字符串,fillchar不指定时默认为空格 ```python >>> a="hello world" >>> a.rjust(20) ' hello world' >>> a.rjust(20,'x') 'xxxxxxxxxhello world' ``` * (11)ljust(width,fillchar=' '),返回一个原字符串左对齐,并使用fillchar指定的字符填充至width长度的字符串,fillchar不指定时默认为空格 ```python >>> a="hello world" >>> a.ljust(20) 'hello world ' >>> a.ljust(20,'x') 'hello worldxxxxxxxxx' ``` * (12)center(width,fillchar=' '),返回一个原字符串居中对齐,并使用fillchar指定的字符填充到width长度的字符串,fillchar不指定时默认为空格 ```python >>> a="hello world" >>> a.center(20) ' hello world ' >>> a="hello world" >>> a.center(20,'x') 'xxxxhello worldxxxxx' ``` * (13)count(sub,start=0,end=len(string)),返回字符串包含子串的数量,可以指定查询的起始位置和结束位置,不指定则默认为整个字符串中计数 ```python >>> a="hello world" >>> a.count('l') 3 >>> a.count('l',1,5) 2 >>> a="hello world hello world hello" >>> a.count("hello") 3 ``` * (14)index(sub,start=0,end=len(string)),返回字符串中查找到的第一个子串的起始位置索引值,可以指定查找起始和结束范围,若查找不到则报ValueError的异常 ```python >>> a="hello world" >>> a.index('h') 0 >>> a.index('x') Traceback (most recent call last): File "
", line 1, in
ValueError: substring not found >>> a.index('l',5,20) 9 >>> a="hello world hello world" >>> a.index("world") ``` * (15)rindex(sub,start=0,end=len(string)) 返回字符串中查找到的最后一个子串的起始位置的索引值,可以指定查找起始和结束范围,若查找不到则报ValueError的异常 ```python >>> a="hello world" >>> a.rindex("l") 9 >>> a.rindex("l",0,5) 3 >>> a="hello world hello world hello" >>> a.rindex("world") 18 ``` * (16)find(sub,start=0,end=len(string)) 返回字符串中查找到的第一个子串的起始位置索引值,可以指定查找起始和结束范围,若查找不到则返回-1 ```python >>> a="hello world" >>> a.find('l') 2 >>> a.find('x') -1 >>> a.find('l',6,10) 9 >>> a="hello world hello world" >>> a.find("world") 6 ``` * (17)rfind(sub,start=0,end=len(string)) 返回字符串中查找到最后一个子串的起始位置索引,可以指定查找起始和结束范围,若查找不到则返回-1 ```python >>> a="hello world" >>> a.rfind('l') 9 >>> a.rfind('x') -1 >>> a.rfind('l',1,6) 3 ``` * (18)split(rep=None,maxsplit=-1) 将字符串根据sep分割,如果sep不填则默认使用空格分割,如果maxsplt不指定则默认将根据字符串中所有的sep分割,否则分割指定的数目 ```python >>> a="hello world hello world hello world" >>> a.split() ['hello', 'world', 'hello', 'world', 'hello', 'world'] >>> a.split(" ",2) ['hello', 'world', 'hello world hello world'] >>> a.split("world") ['hello ', ' hello ', ' hello ', ''] >>> a.split('x') ['hello world hello world hello world'] ``` * (19)split(rep=None,maxsplit=-1) 将字符串从右侧开始根据sep分割,如果sep不填则默认使用空格分割,如果maxsplt不指定则默认将根据字符串中所有的sep分割,否则分割指定的数目 ```python >>> a="hello world hello world hello world" >>> a.rsplit() ['hello', 'world', 'hello', 'world', 'hello', 'world'] >>> a.rsplit(" ") ['hello', 'world', 'hello', 'world', 'hello', 'world'] >>> a.rsplit(" ",2) ['hello world hello world', 'hello', 'world'] >>> a.rsplit("world") ['hello ', ' hello ', ' hello ', ''] ``` * (20)splitlines(keepends=False) 按照换行符(\r,\r\n,\n)分割,如果keepends不填默认为False,则返回的每一行没有回车符,如果keepends设置为True则每一行带有换行符 ```python >>> a="hello world 01\n hello world 02\r hello world 03 \r\n hello world 04" >>> a 'hello world 01\n hello world 02\r hello world 03 \r\n hello world 04' >>> a.splitlines() ['hello world 01', ' hello world 02', ' hello world 03 ', ' hello world 04'] >>> a.splitlines(True) ['hello world 01\n', ' hello world 02\r', ' hello world 03 \r\n', ' hello world 04'] ``` * (21)partition(sep) 根据指定的sep将字符串分割,返回一个三元组,第一个元素为分割符左边的部门,第二个元素为分隔符本身,第三个元素为分隔符有点的部分,若字符串中没有找到分隔符sep,则返回一个三元组,第一个元素为字符串本身,第二个第三个为空字符串 ```python >>> a="hello world hello world" >>> a.partition(" ") ('hello', ' ', 'world hello world') >>> a.partition('x') ('hello world hello world', '', '') ``` * (22)rpartition(sep) 根据指定的sep将字符串从右侧开始查找并分割,返回一个三元组,第一个元素为分割符左边的部门,第二个元素为分隔符本身,第三个元素为分隔符有点的部分,若字符串中没有找到分隔符sep,则返回一个三元组,第一个元素为字符串本身,第二个第三个为空字符串 ```python a="hello world hello world" >>> a.rpartition(" ") ('hello world hello', ' ', 'world') ``` * (23)replace(old,new,count=-1) 将字符串中的old替换为new,如果不指定count则全部替换,否则按照count指定的数目替换 ```python >>> a="hello world hello world hello world" >>> a.replace("hello","Hello") 'Hello world Hello world Hello world' >>> a.replace("hello","Hello",1) 'Hello world hello world hello world' ``` * (24)zfill(width) 将字符串用0填充至width指定的长度,若指定的长度比字符串长度还小,则不作任何操作 ```python >>> a="hello world" >>> a.zfill(20) '000000000hello world' >>> a.zfill(4) 'hello world' ``` * (25)join(iterable) 将列表中的元素以指定的字符连接为新的字符串 ```python >>> a=["hello","world","hello","world","hello","world"] >>> " ".join(a) 'hello world hello world hello world' >>> 'x'.join(a) 'helloxworldxhelloxworldxhelloxworld' >>> '\n'.join(a) 'hello\nworld\nhello\nworld\nhello\nworld' ``` * (26)format() 字符串格式化 * 1) format使用位置对字符串进行字符串进行变量替换 ```python >>> "{} {}".format("hello","world") 'hello world' >>> "{0} {1}".format("hello","world") 'hello world' >>> "{1} {0} {1}".format("hello","world") 'world hello world' ``` * 2)使用参数指定对字符串进行变量替换 ```python >>> "{v1} {v2}".format(v1="hello",v2="world") 'hello world' >>> "{v1} this is a string {v2}".format(v2="world",v1="hello") 'hello this is a string world' ``` * 3)数字格式化 ```python >>> a=3.141592653 >>> "{:.2f}".format(a) '3.14' >>> "{: .2f}".format(a) ' 3.14' >>> "{:.0f}".format(a) '3' >>> a=1000000000 >>> "{:0>12d}".format(a) '001000000000' >>> "{:x<12d}".format(a) '1000000000xx' >>> "{:,}".format(a) '1,000,000,000' >>> "{:.2e}".format(a) '1.00e 09' >>> "{:>15d}".format(a) ' 1000000000' >>> "{:<15d}".format(a) '1000000000 ' >>> "{:^15d}".format(a) ' 1000000000 ' >>> "{:.2%}".format(0.25) '25.00%' >>> '{:b}'.format(11) '1011' >>> '{:d}'.format(11) '11' >>> '{:o}'.format(11) '13' >>> '{:x}'.format(11) 'b' >>> '{:#x}'.format(11) '0xb' >>> '{:#X}'.format(11) '0XB' ``` * (27)format_map() 使用字典格式的数据对字符串进行变量替换 ```python >>> info={"v1":"hello","v2":"world"} >>> "{v1} {v2}".format_map(info) 'hello world' ``` * (28)encode(encoding="utf-8",errors='strict') 以指定的编码格式编码字符串,默认的是utf-8,errors指定不同的错误处理方案 strict意为编码错误引起一个UnicodeError,其他可选的值有: 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值 ```python >>> "hello world".encode("utf-8") b'hello world' >>> "hello world".encode("gbk") b'hello world' >>> "hello world".encode("ascii") b'hello world' >>> "你好,世界!".encode("utf-8") b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81' >>> "你好,世界!".encode("gbk") b'\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7\xa3\xa1' >>> "你好,世界!".encode("ascii") Traceback (most recent call last): File "
", line 1, in
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) >>> "你好,世界!".encode("ascii","ignore") b'' ``` * (29)maketrans() 创建字符映射的转换表,可以是一个参数,一个参数是时必须为字典dict,返回的类型为dict,key和value均用Unicode编码表示,也可以接受两个参数,如果是两个参数,则两个参数的类型为字符串str类型,并且两个参数的额字符串长度相同,以此来建立对应位置的映射关系 ```python >>> str.maketrans({"a":1,"b":2,"c":3}) {97: 1, 98: 2, 99: 3} >>> str.maketrans("hello","world") {104: 119, 101: 111, 108: 108, 111: 100} ``` * (30)translate(table) 根据maketrans生成的映射表对字符串进行字符替换,如果转换表中字符对应的value值为None的,则在此字符串中删除此字符 ```python >>> table=str.maketrans("hello","world") >>> "hello world hello world".translate(table) 'wolld wdrld wolld wdrld' >>> table=str.maketrans({"h":"w","e":None,"l":"o","o":None}) >>> "hello world".translate(table) 'woo wrod' ``` * (31)expandtabs(tabsize=8) 吧字符串中的tab字符\t转换为指定数量的空格,默认为8个 ```python >>> "hello\tworld".expandtabs(tabsize=8) 'hello world' >>> "hello\tworld".expandtabs(tabsize=4) 'hello world' >>> "hello\tworld".expandtabs(tabsize=16) 'hello world' ``` * (32)startswith(prefix,start=0,end=len(string)) 判断字符串是否已给定的prefix为起始,如果是返回True,否则返回False,同时可以指定判断起始的位置。start和end默认为0和字符串的长度. prefix还可以是一个有字符串元素组成的元组,只要有一个匹配上,即返回True,否则返回False ```python >>> a="hello world" >>> a.startswith("h") True >>> a.startswith("hello") True >>> a.startswith(" ",5,10) True >>> a.startswith(" ",3,10) False >>> a.startswith(("haha","hehe","h","w")) True >>> a.startswith(("haha","hehe","m","w")) False ``` * (33)endswith(suffix,start=0,end=len(string)) 判断字符串是否已给定的suffix为结尾,如果是返回True,否则返回False,同时可以指定判断起始的位置。start和end默认为0和字符串的长度. suffix还可以是一个有字符串元素组成的元组,只要有一个匹配上,即返回True,否则返回False ```python >>> a="hello world" >>> a.endswith("d") True >>> a.endswith("world") True >>> a.endswith("d",0,4) False >>> a.endswith(("hello","heheh","word","wd","d")) True >>> a.endswith(("hello","heheh","word","wd","h")) False ``` * (34)isupper() 如果字符串的所有字符都是大写,则返回True,否则返回False ```python >>> "HELLO".isupper() True >>> "HeLLO".isupper() False >>> "HELLO WORLD".isupper() True >>> " ".isupper() False ``` * (35)islower() 如果字符串的所有字符都是小写,则返回True,否则返回False ```python >>> "hello world".islower() True >>> "Hello world".islower() False >>> " ".islower() False ``` * (36)istitle() 判断字符串中是否每个单词的首字母都睡大写,如果是返回True,否则返回False ```python >>> "Hello World".istitle() True >>> "Hello world".istitle() False ``` * (37)isspace() 如果字符串中的所有的字符都是空格,并且至少有一个字符,则返回True,否则返回False ```python >>> "".isspace() False >>> " ".isspace() True >>> " ".isspace() True >>> "\t".isspace() True >>> "\n".isspace() True ``` * (38)isprintable() 如果字符串中所有字符都可打印返回True,否则返回False ```python >>> "hello ".isprintable() True >>> " ".isprintable() True >>> "".isprintable() True >>> "\t".isprintable() False >>> "\n".isprintable() False >>> "\r".isprintable() False >>> "hello\nworld".isprintable() False ``` * (39)isnumeric() 如果字符串中所有字符均有数字组成,返回True,否则返回False ```python >>> "hello".isnumeric() False >>> "1234567890".isnumeric() True >>> "0123".isnumeric() True >>> " 0234 ".isnumeric() False >>> "".isnumeric() False ``` * (40)isidentifier() 判断字符串是否为python的有效的标识符,python有效的额标识符为字母或下划线开头,由数字字母和下划线组成的 ```python >>> "hello".isidentifier() True >>> "def".isidentifier() True >>> "1abc".isidentifier() False >>> "class".isidentifier() True >>> "a-b".isidentifier() False ``` * (41)isdigit() 如果字符串中所有字符均有数字组成,返回True,否则返回False ```python >>> "123".isdigit() True >>> "a12".isdigit() False >>> "0123".isdigit() True >>> "".isdigit() False ``` * (42)isdecimal() 如果字符串中所有字符均有十进制字符组成,返回True,否则返回False ```python >>> "0123456789".isdecimal() True >>> "0b11".isdecimal() False >>> "a0".isdecimal() False ``` * (43)isascii() 如果字符串中所有字符均为ascii范围内编码,则返回True,否则返回False ```python >>> "hello world".isascii() True >>> "你好".isascii() False ``` * (44)isalpha() 如果字符串中至少有一个字符并且所有字符都是字母,则返回True,否则返回False ```python >>> "hello world".isalpha() False >>> "helloworld".isalpha() True >>> "abc123".isalpha() False ``` * (45)isalnum() 如果字符串中每个字符都是由字母或者数字组成,则返回True,否则返回False ```python >>> "hello world".isalnum() False >>> "helloworld".isalnum() True >>> "abc123".isalnum() True ```
始终坚持开源开放共享精神,同时感谢您的充电鼓励和支持!
版权所有,转载本站文章请注明出处:redrose2100, http://blog.redrose2100.com/article/80
上一篇:
Python基本数据类型----数字类型
下一篇:
Python中的列表及其常用方法
搜索
个人成就
出版书籍
《Pytest企业级应用实战》
测试开发技术全栈公众号
测试开发技术全栈公众号
DevOps技术交流微信群
加微信邀请进群
常用网站链接
开源软件洞察
云原生技术栈全景图
Python语言官方文档
Golang官方文档
Docker官方文档
Jenkins中文用户手册
Scrapy官方文档
VUE官方文档
Harbor官方文档
openQA官方文档
云原生开源社区
开源中国
Kubernetes中文文档
Markdown语法官方教程
Kubernetes中文社区
Kubersphere官方文档
BootStrap中文网站
JavaScript中文网
NumPy官方文档
Pandas官方文档
GitLink确实开源网站
数据库排名网站
编程语言排名网站
SEO综合查询网站
数学加减法练习自动生成网站
Kickstart Generator
文章分类
最新文章
最多阅读
特别推荐
×
Close
登录
注册
找回密码
登录邮箱:
登录密码:
图片验证码:
注册邮箱:
注册密码:
邮箱验证码:
发送邮件
注册邮箱:
新的密码:
邮箱验证码:
发送邮件