# 字符串中的元素:單個字母,數字,漢字。單個字符都稱為元素。
s = 'hello!'
1.len(數據):統計數據的長度
print(len(s)) # 6
2.字符串取值:字符串名[索引值]
# 正向索引:0,1,2……從0開始
# 反向索引:……-6,-5,-4,-3,-2,-1
print(s[5]) # 索引,! print(s[-1]) # !
# 字符串取多個值:切片 字符串名[索引頭:索引尾:步長]步長默認為1
print(s[1:5:2]) # el # 取頭不取尾1,3 print(s[1:5]) # ello # 1,2,3,4 print(s[2:4:2]) # l # 2 print(s[:]) # hello! # 取全部 print(s[:4]) # hell # 取3之前的全部0,1,2,3 print(s[3:]) # lo! # 3以后的全取 3,4,5 print(s[-1:-7:-1]) # 倒序輸出:!olleh print(s[::-1]) # 倒序輸出:!olleh
3.字符串分割 字符串.split('可以指定切割符號',指定切割次數)---只有字符串可以使用,返回一個列表類型的數據,列表中的子元素都是字符串類型
print(s.split('e')) # ['h', 'llo!'] print(s.split('l')) # ['he', '', 'o!'] print(s.split('l', 1)) # ['he', 'lo!']
4.字符串的替換 字符串.replace('可以指定替換值','新值',指定替換次數)
s1 = 'heelo!' new = s1.replace('o', '@') print(new) # heel@! new1 = s1.replace('e', '1', 2) print(new1) # h11lo!
5.字符串的去除指定字符 字符串.strip('指定去除字符',指定替換次數)
# 只去掉頭和尾的字符,不能去除直接字符
s = ' hello ' new3 = s.strip() # 默認去空格 print(new3) # hello new4 = s.strip(' he') print(new4) # llo
6.字符串的拼接+ 保證+左右兩邊的變量值的類型一致
s_1 = 'python,' s_2 = 'welcome!' s_3 = 666 print(s_1 + s_2 + str(s_3 )) # s_3強制轉換后才能拼接 # python,welcome!666 print(s_1, s_2, s_3) # python, welcome! 666
7.字符串格式化輸出 % format
age = 18 name = 'zhengzi' print("歡迎進入" + str(age) + "歲的" + name + "的博客園") # 歡迎進入18歲的zhengzi的博客園 # (1)格式化輸出1:format 用{}來占位 print("歡迎進入{}歲的{}的博客園".format(age, name)) # 歡迎進入18歲的zhengzi的博客園,默認順序 print("歡迎進入{1}博客園,她今年{0}".format(age, name)) # 歡迎進入zhengzi博客園,她今年18 # (2)格式化輸出2:% %s字符串(任何數據), %d數字(整型) %f浮點數 (%.2f四舍五入保留兩位小數) print("歡迎進入%d歲的%s的博客園" % (age, name)) # 歡迎進入18歲的zhengzi的博客園