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():查找某個元素的個數(shù)
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表示替換的個數(shù)矮嫉,沒有參數(shù)2默認全部替換
print(res1)#javat66t
print(res2)#javat66tjavat66t
- split():字符串分割
str1 = 'aaa1bbb1ccc1'
res1 = str1.split('1')
#split('1',2) 2表示分割次數(shù)
print(res1)#['aaa','bbb','ccc','']
- upper():將字母轉(zhuǎn)換成大寫
str1 = 'abc123'
res1 = str1.upper()
print(res1)#ABC123
- lower():將字母轉(zhuǎn)換成小寫
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:帚戳,bb:{a},cc:{c}".format(a=11,b=22,c=33)
print(res4)#aa:22,bb:11,cc:33
format格式化小數(shù)
numbe = 2.56789
res5 = "今天的白菜價格為:{:.2f}".format(number) #.2f表示保留幾位小數(shù)
print(res5) #今天的白菜價格為:2.57
image.png
- 2玷或、傳統(tǒng)的格式化輸出%
%s-----格式化字符串
%d-----格式化整數(shù)
%f -----格式化浮點數(shù)儡首,可指定小數(shù)點后精度
res1 = "名字:%s,年齡:%d,成績:%.2f"%('小明',18偏友,98.5)