標籤:資料 匹配 strip case lower class 16px font style
字串是python中最常用的資料類型,我們可以使用單引號(‘ ‘)或雙引號(" ")來建立字串。
a=‘Hello‘b="Hello"
所有標準序列操作如(索引,分區,成員資格,求長度,取最小值和最大值等),對字串同樣適用。
字串常用的格式化符號:
(%s 格式化字串)
print(‘Hello,%s‘%‘world‘) #使用%s作為‘world‘的預留位置Hello,world #結果print(‘還有%s天‘%10) #使用%d作為10的預留位置還有10天 #結果#%s不僅可以格式化字串,還可以格式化整數
(%d 格式化整數)
print(‘還有%d天‘%10) #使用%d作為10的預留位置還有10天 #結果
字串常用的方法:
find():用於檢測字串中是否包含子字串str,可以指定開始和結束的範圍。
a=‘hello,world‘print(a.find(‘wo‘))6 #返回了匹配值的索引print(a.find(‘kb‘))-1 #找不到,返回-1
print(a.find(‘wo‘,3)) #提供起點6 #結果print(a.find(‘wd‘,6))-1 #結果
print(a.find(‘wo‘,3,8)) #提供起點和終點6 #結果print(a.find(‘wd‘,3,7))-1 #結果
lower():將字串中所有大寫字元轉換為小寫
a=‘HeLlo‘b=a.lower()print(b)hello #結果
upper():將字串中所有小寫字元轉換為大寫
a=‘HeLlo‘b=a.upper()print(b)HELLO #結果
swapcase():將字串中所有小寫字元轉換為大寫,大寫字元轉換為小寫
a=‘HeLlo‘b=a.swapcase()print(b)hElLO #結果
replace():把字串中的舊字串替換成新字串
a=‘hello world‘b=a.replace(‘hello‘,‘HELLO‘)print(b)HELLO world #結果
strip():移除字串頭尾指定字元
a=‘++hello world++‘b=a.strip(‘+‘)print(b)hello world #結果b=a.strip(‘++h‘)print(b)ello world #結果b=a.strip(‘++d‘)print(b)hello worl #結果
(自興人工智慧)python字串