文章目录
初始化方式
不同于C++和Java,Python中没有字符类型,单引号和双引号都用于字符串,可以互相嵌套。
s = 'this is an "example"'
print(s)
# 输出:this is an "example"
求长度
函数len()
用法:length(s)
参数:string类
返回:string类的长度
s = "abcdef"
print(len(s))
# 输出:6
CRUD
插入
多个字符串拼接
可以直接用’+’号拼接两个字符串
s1 = "abc"
s2 = "def"
s3 = s1 + s2
print(s3)
# 输出:abcdef
在指定位置插入字符串
因为Python的string类是不可变的,所有没有直接的插入函数可用,一般用切片+拼接
# 在s位置3处插入ins字符串
s = "abcdef"
ins = "123"
s = s[:3] + ins + s[3:]
print(s)
# 输出:abc123def
查找
访问指定位置的字符
直接通过下标访问
s = "abcdef"
print(s[2])
# 输出:c
查找指定区间的子串
切片s[left: right],左闭右开
s = "abcdef"
print(s[2:5])
# 输出:cde
查找指定内容的子串
成员函数.index()和.find()
用法:s.index(subs) s.find(subs)
参数:subs为要查找的子串
返回:返回子串开始的下标值,如果不存在,.index()会报错,.find()返回-1
s = "abc123def"
print(s.index("123")) # 输出:3
print(s.find("123")) # 输出:3
print(s.find("xyz")) # 输出:-1
print(s.index("xyz")) # 运行出错 ValueError: substring not found
修改
修改指定位置的字符(串)
举例:把s中位置2的字符改为’X’
和插入的思想类似,用切片
s = "abc123"
s = s[:2] + 'X' + s[2:]
print(s)
# 输出:s = "abc123"
替换指定内容
举例:把s中的”abc”替换成”123”
成员函数.replace()
用法:s.replace(old,new,max)
参数:old为要更换的旧字符(串), new为新字符(串), max是替换多少次, 默认是全部
返回:s替换后的值,但s本身不会改变(因为string是不可变类型)
s1 = "abcxyzabcxyz"
s2 = "abcxyzabcxyz"
s1 = s1.replace("abc","ABC")
s2 = s2.replace("abc","ABC",1)
print(s1) # 输出:ABCxyzABCxyz
print(s2) # 输出:ABCxyzabcxyz
删除
删除指定区间的子串
和修改子串的思路类似,用切片和’+’号拼接实现
// 删除[2,4]的子串
s = "0123456"
s = s[:2] + s[5:]
print(s)
# 输出:0156
删除指定内容
用.replace()将要删除的子串替换成””
s1 = "abcxyzabcxyz"
s2 = "abcxyzabcxyz"
s1 = s1.replace("abc","")
s2 = s2.replace("abc","",1)
print(s1) # 输出:xyzxyz
print(s2) # 输出:xyzabcxyz
其他常用函数
判断相关
.isalpha() #是否全是字母
.isdigit() #是否全是数字
.isspace() #是否全是空格
s1 = "abc123"
print(s1.isalpha()) # False
print(s1.isdigit()) # False
s2 = "abc"
print(s2.isalpha()) # True
s3 = "123"
print(s3.isdigit()) # True
s4 = " "
print(s4.isspace()) # True
大小写转换相关
.lower() — 全部小写
.upper() — 全部大写
.title() — 各个单词的首字母大写
.capitalize() — 首字母大写
注意:因为Python中字符串类型是不可改变的,所以这些成员函数只能返回修改后的字符串,而不能修改原字符串
s = "this is an example"
print(s.lower()) # this is an example
print(s.upper()) # THIS IS AN EXAMPLE
print(s.title()) # This Is An Example
print(s.capitalize()) # This is an example
去除空格相关
.strip() — 删除两边空格
.lstrip() — 删除左边空格
.rstrip() — 删除右边空格
.replace(" “,”") — 删除所有空格
s = " this is an example "
print(s.strip()) # this is an example
print(s.lstrip()) # this is an example[空格][空格][空格]
print(s.rstrip()) # [空格][空格][空格]this is an example
print(s.replace(" ","")) # thisisanexample
拆分/组装
.split(sep[,maxsplit]) — 将字符串按指定字符串进行分割
参数:sep为分割的依据,maxsplit为最大分割次数,不指定的话就全部分割
返回:分割后的各个字符串组成的列表
s = "this is an example"
arr1 = s.split(" ")
print(arr1) # ['this', 'is', 'an', 'example']
arr2 = s.split(" ", 1)
print(arr2) # ['this', 'is an example']
str.join(seq)
参数:seq为一个字符串列表
返回:将seq中的字符串用str连接后形成的字符串
arr = ['this', 'is', 'an', 'example']
s = "&".join(arr)
print(s)
# 输出:this&is&an&example
其他
eval(str) — 直接计算数学表达式
参数:str是一个数学表达式
返回:直接解析然后返回计算结果
s = "2*5+3"
print(eval(s))
# 输出:13