目录
字符串常用方法
1.大小写转换的常用方法
1、 str_1.upper(): 全部大写
2、 str_02.lower(): 全部小写
3、 str_3.capitalize(): 首字母大写
4、 str_4.title(): 每一个单词首字母大写
5、 str_5.swapcase() : 大小写相互转换
str_1 = 'hello python'
new_str_1 = str_1.upper() # 把单词小写字母全部转换为大写
print(new_str_1)
str_2 = 'HELLO PYTHON'
new_str_2 = str_2.lower() # 把单词大写字母全部转换为小写
print(new_str_2)
str_3 = 'hello python'
new_str_3 = str_3.capitalize() # 首字母大写,仅转换第一个单词首字母
print(new_str_3)
str_4 = 'hello python PYTHON'
new_str_4 = str_4.title() # 每一个单词首字母大写,如果有字母全部大写会保留首字母大写其他字母转换
print(new_str_4)
str_5 = 'hello python PYTHON'
new_str_5 = str_5.swapcase() # 大小写进行转换(所有字母)
print(new_str_5)
2.字符串统计相关常用方法
1、count():统计字符在字符串中出现的次数
语法:str.count(sub, start= 0,end=len(string))
sub:需要统计的字符
start:统计范围开始索引值
end:统计范围结束索引值
返回:sub在字符串指定范围内出现的次数
注意:只输入sub,开始索引值和结束索引值不输,默认查找整个字符串
str = 'hello python'
new_str1 = str.count('h')
print(new_str1)
new_str2 = str.count('h', 0, 3)
print(new_str2)
new_str3 = str.count('h', 1, 3)
print(new_str3)
2、find():查找字符在字符串中的索引位置
语法:str.find(str, beg=0, end=len(string))
str : 需要查询找的字符
beg :统计范围开始索引值,默认为0。
end : 统计范围结束索引,默认为字符串的长度
返回:默认只查询第一次找到的字符,然后返回索引值
注意:只输入str,开始索引值和结束索引值不输,默认查找整个字符串
str = 'hello python'
new_str1 = str.find('h') # 从下标0开始,查找在字符串里第一个出现的子串
print(new_str1)
new_str2 = str.find('h', 1, ) # 从下标1开始,查找在字符串里第一个出现的子串
print(new_str2)
new_str3 = str.find('h', 1, 3) # 查找不到返回-1
print(new_str3)
3.拆分&替换
1、拆分:split()
split() :字符串拆分默认是通过空格键拆分的,可以自己指定拆分字符,拆分过程中会将指定的拆分字符丢弃
语法:str.split(str="", num=string.count(str))
str :分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num :控制拆分次数。默认为 -1, 即分隔所有。
str = 'abcd abcd'
new_str1 = str.split('b') # 以字符b为分隔字符,不限次拆分
print(new_str1)
new_str2 = str.split('b', 1) # 以字符b为分隔字符,拆分1次
print(new_str2)
new_str3 = str.split() # 默认以空格拆分
print(str)
print(new_str3)
2、替换:replace()
语法:str.replace(old, new[, max])
old : 将被替换的字符
new : 替换后的字符
max : 可选字符串, 要替换的次数
可以替换任意字符包括空格
返回:替换后新的字符
str = 'hello python'
new_str1 = str.replace('h', 'w')
print(new_str1) # h替换成w不输入次数默认替换全部
new_str2 = str.replace('h', 'w', 1)
print(new_str2) # h替换成w输入次数,替换一次
new_str3 = str.replace('e', ' ')
print(new_str3) # e替换成空格
4.字符串连接:join()
语法:str.join(sequence)
sequence :要连接的元素序列
new_str = '*'.join(str_1)
通过制定的字符串(*)连接str_1
str_1='hello python'
new_str = '*'.join(str_1)
print(new_str)
5.字符串格式化
1、 %
%s:字符串占位符,如果传的不是字符串,会发生强制类型转换
%d:int类型占位符
str_1 = 'my name is %s' % ('xiaoming')
print(str_1)
str_2 = 'my age is %d' % (10)
print(str_2)
print("我叫 %s 今年 %d 岁!" % ('小明', 10))
2、 format()
#1、按顺序取值
#参数的个数要大于占位符个数,只能多不能少
price = "the price is {} {} {}".format(10.99,100,200)
#2、按索引取值(0开始)
price ="the price is {0} {1} {1}".format(100,200)
#3、按关键字取值
price ="the price is {price1} {price1} {price2}".format(price2=200,price1=100)
#4、调整精度
price ="the price is {:.2f}".format(12.5364675)
#5、百分比格式化
price ="the price is {:.2%}".format(0.5364675)