一、字符串拆分
1、语法:字符串.split("拆分字符",maxsplit=拆分次数),返回list
2、例子:
test_str = "aa bb cc dd"
new_str_list = test_str.split(" ")
结果:
['aa', 'bb', 'cc', 'dd']
3、注意:
(1)返回list
(2)拆分字符会被丢弃
(3)当拆分字符是第一个或者是最后一个,此时list里会增加一个空字符串
(4)如果拆分字符不传,默认按空格拆分
(5)如果在中间有两个拆分字符连续出现,此时拆分的时候会出现1个空格(2个拆分字符中间什么都没有,默认为空格)
二、字符串连接
1、语法:"连接字符".join(字符串)
2、例子
test_list = ["I","LOVE","PYTHON"]
rusult2 = "-".join(test_list)
结果:
"I-Love-PYTHON"
三、字符串替换
1、语法:
result = 字符串.replace(old,new,count)
#old:需要替换掉的字符
#new:需要放进去的字符
#count:替换次数,默认是全部替换
2、例子
test = "hhahhsdfw"
result = test_str.replace("h","&")
结果:&&a&&sdfw
result2 = test_str.replace("h","&",3)#指定替换3次
结果:&&a&hsdfw
四、字符串的成员运算
1、in :在 就返回True
2、not in:不在 就返回True
test_str = "hhahhsdfw"
print("aa" in test_str)
返回:False
print("aa" not in test_str)
返回:True
五、字符串格式化
1、%s 字符串占位符
price1 = "this phone is %s" %("100")
price2 = "this phone is %s" %(100)#如果后面放的不是字符串,会强制给你转成字符串
print(price1)
print(price2)
结果:
this phone is 100
this phone is 100
2、%d 数值占位符
price1 = "this phone is %d" %(100)
price2 = "this phone is %d" %(-100)
price3 = "this phone is %d" %(99.99)#如果是小数,会强制把小数部分抹掉
print(price1)
print(price2)
print(price3)
结果
this phone is 100
this phone is -100
this phone is 99
3、%f 浮点数的占位符
price1 = "this phone is %f" %(100)#默认精确到6位小数
price2 = "this phone is %.2f" %(100)#后面保留2位小数
print(price1)
print(price2)
结果:
this phone is 100.000000
this phone is 100.00
4、format
(1)按顺序取值
price1 = "this phone is {}".format(99.99)#format中可以放任意数据类型
price2 = "this phone is {}".format([1,2,3,4,5])
print(price1)
print(price2)
结果
this phone is 99.99
this phone is [1, 2, 3, 4, 5]
(2)按索引取值
info = "my name is {1} age is {0} job is{2} city is{3}".format("老王",20,"测试工程师","深圳")
print(info)
结果:
my name is 20 age is 老王 job is测试工程师 city is深圳
(3)按关键字取值
info = "my name is {name} age is {age} job is{job} city is {city}".format(name="老王",age=20,job="测试工程师",city="深圳")
print(info)
结果:
my name is 老王 age is 20 job is测试工程师 city is 深圳
5、f
name="刘德华"
age = 20
city = "深圳"
job = "测试工程师"
info = f"my name is {name} age is {age} job is{job} city is {city}"
print(info)
结果
my name is 刘德华 age is 20 job is测试工程师 city is 深圳
欢迎来到testingpai.com!
注册 关于