1、字符串常用方法
- join():字符串拼接
str1 = 'python'
str2 = 'java'
res = ''.join((str1,str2))
print(res)
# pythonjava
- find():查找字符串位置(找到第一个,返回开始的下标位置,没找到返回-1)
str1 = 'python'
str2 = 'python6t6t6t'
res1 = str1.find('t')
res2 = str2.find('t')
res3 = str1.find('thon')
print(res1)#2
print(res2)#2
print(res3)#2
- count():查找某个元素的个数
str1 = 'python6t6t6t'
c = str1.count('t')
c2 = str1.count('th')
print(c)#4
print(c2)#1
- replace():替换字符
str1 = 'pythont66t'
str2 = 'pythont66tpythont66t'
res1 = str1.replace('python','java')
res2 = str1.replace('python','java',2)#2表示替换的个数,没有参数2默认全部替换
print(res1)#javat66t
print(res2)#javat66tjavat66t
- split():字符串分割
str1 = 'aaa1bbb1ccc1'
res1 = str1.split('1')
#split('1',2) 2表示分割次数
print(res1)#['aaa','bbb','ccc','']
- upper():将字母转换成大写
str1 = 'abc123'
res1 = str1.upper()
print(res1)#ABC123
- lower():将字母转换成小写
str1 = 'ABC123'
res1 = str1.lower()
print(res1)#abc123
2、字符串格式化输出
- 1、format格式化输出
str1 = "我是{},今年{}岁"
print(str1.format('张三',18))
#我是张三,今年18岁
#默认占几个位置,传几个值
res1 = "aa:{},bb:{},cc:{}".format(11,22,33)
print(res1)#aa:11,bb:22,cc:33
#按位置传值
res2 = "aa:{2},bb:{0},cc:{1}".format(11,22,33)
print(res2)#aa:33,bb:11,cc:22
res3 = "aa:{0},bb:{0},cc:{1}".format(11,22)
print(res3)#aa:11,bb:11,cc:22
#格式化输出
res4 = "aa:{b},bb:{a},cc:{c}".format(a=11,b=22,c=33)
print(res4)#aa:22,bb:11,cc:33
format格式化小数
numbe = 2.56789
res5 = "今天的白菜价格为:{:.2f}".format(number) #.2f表示保留几位小数
print(res5) #今天的白菜价格为:2.57
image.png
- 2、传统的格式化输出%
%s-----格式化字符串
%d-----格式化整数
%f -----格式化浮点数,可指定小数点后精度
res1 = "名字:%s,年龄:%d,成绩:%.2f"%('小明',18,98.5)