字符串相關處理
字符串拼接
temp1 = "我是"
temp2 = "皮皮江"
temp = temp1 + temp2
print(temp)
我是皮皮江
重複字符
>>> 'hello' * 3
'hellohellohello'
字符串格式化
- %格式化
%s : str
%d : int
%f : float
%.nf : float,指定小數點,n小數保留位數
>>> name = "pipijiang"
>>> age = 18
>>> print("my name is %s , my age is %d" %(name,age))
my name is pipijiang , my age is 18
2.format()函數,格式化函數
字符串使用{ 0 },{ 1 },{ 2 }….{ n }來佔位,使用format()來從左到右依次填充佔位的內容
>>> name = "pipijiang"
>>> age = 18
>>>> print("name:{0} age:{1}".format(name,age))
name:pipijiang age:18
>>> print("name:{} age:{}".format(name,age)) #省略了也可以
name:pipijiang age:18
字符分隔函數
split(str) 使用str進行切割
不傳參則使用空字符串進行切割
>>> "10,20,30".split(",")
['10', '20', '30']
>>> x, y, z = "10,20,30".split(",")
>>> x
'10'
>>> y
'20'
>>> z
'30'
>>>
外門邪道修改字符串
>>> s = "I am pipijiang"
>>> l = list(s)
>>> s
'I am pipijiang'
>>> l
['I', ' ', 'a', 'm', ' ', 'p', 'i', 'p', 'i', 'j', 'i', 'a', 'n', 'g']
>>> l[0] = "You"
>>> l
['You', ' ', 'a', 'm', ' ', 'p', 'i', 'p', 'i', 'j', 'i', 'a', 'n', 'g']
>>> "".join(l) #使用空格連接列表中的每個元素,生成一個字符串
'You am pipijiang'
>>>
字符串索引
>>> s = "IamPipijiang"
>>> s[3:5] #從索引爲3的開始取,取到索引爲5-1個
'Pi'
>>> s[::2] ##從第0個開始取值,每取一個再取後面的第二個
'Imiiin'
>>> s[::-1] #反轉字符串
'gnaijipiPmaI'
字符串方法
1) S.find(sub[, start[, end]]) -> int查找字符串
功能: 查找字符串的字符的位置
找到多查找的字符串默認返回字符第一次出現的索引
找不到返回 -1
start: 可選參數 開始索引位置
end:可選參數 結束索引位置,且不包含結束位置的內容
>>> s = "hello,我是pipijiang"
>>> s.find("我")
6 #找到返回字符索引
>>> s.find("江")
-1 #找不到返回-1
2) 字母大小寫
3) def replace(self, old: str, new: str, count: int = …)字符串替換
old: str 要替換的字符串
new: str 替換後的字符串
count: int 要替換幾個,從第一個開始
4) 翻譯表str.maketrans(instr,outstr)
功能: 將instr和outstr兩個字符串中的每個字符一一對應起來
srt.maketrans("abc","123") # a-1,b-2,c-3
>>> s = "about you,come in here!"
>>> t = s.maketrans("abc","123") # a-1,b-2,c-3
>>> print(s.translate(t))
12out you,3ome in here!