print("pye", end = ' ') print("pye") print("pye", end = '###')
运行结果:
1 2
>>> pye pye pye###
三、replace替换
1 2 3 4
a = "abcdefgx" print(a) a.replace('e', 'x') print(a)
运行结果:
1 2
>>> abcdefgx abcdxfge
四、切片slice操作
操作和说明
示例
结果
[:] 提取整个字符串
"pyehzmzbrhtwgzm"[:]
"pyehzmzbrhtwgzm"
[start:] 从start索引开始到结尾
"pyehzmzbrhtwgzm"[8:]
"rhtwgzm"
[:end] 从头开始到end-1
"pyehzmzbrhtwgzm"[:8]
"pyehzmzb"
[start:end] 从start到end
"pyehzmzbrhtwgzm"[3:6]
"hzm"
[start:end:step] 从start提取到end,步长是step
"pyehzmzbrhtwgzm"[1:6:2]
"yhm"
倒数三个
"pyehzmzbrhtwgzm"[-3:]
"gzm"
包头不包尾
"pyehzmzbrhtwgzm"[-8:-3]
"brhtq"
倒序
"pyehzmzbrhtwgzm"[::-1]
"mzgwthrbzmzheyp"
五、split()分割和join()合并
1 2 3 4 5 6 7 8
>>> a = "panjoel is a junior high school student" >>> a.split(" ") ["panjoel","is","a","junior","high","school","student"] >>> a.split("junior") ["panjoel is a "," high school student"] >>> b = ["panjoel","is","a","junior","high","school","student"] >>> "*".join(b) "panjoel*is*a*junior*high*school*student"
六、字符串驻留机制和字符串比较
6.1 字符串驻留机制:
对于符合标识符规则的字符串(仅包含下划线,字母,数字),会启用字符串驻留机制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
>>> a = "abd_33" >>> b = "abd_33" >>> a is b True >>> c = "dd#" >>> d = "dd#" >>> c is d False >>> str1 = "aa" >>> str2 = "bb" >>> str1 + str2 is"aabb" False >>> str1 + str2 == "aabb" True
>>> a = "*pyx*is*senior high school student*" >>> a.strip("*") "pyx*is*senior high school student" >>> a.rstrip("*") "*pyx*is*senior high school student" >>> a.lstrip("*") "pyx*is*senior high school student*" >>> " pyx ".strip() "pyx"
7.3 大小写转换
1 2 3 4 5 6 7 8 9 10 11
>>> a = "pye extraordinarily love coding, ardently love programming." >>> a.capitalize() #开头大写 "Pye extraordinarily love coding, ardently love programming." >>> a.title() #各个单词首字母大写 "Pye Extraordinarily Love Coding, Ardently Love Programming." >>> a.upper() #全大写 "PYE EXTRAORDINARILY LOVE CODING, ARDENTLY LOVE PROGRAMMING." >>> a.lower() #全小写 "pye extraordinarily love coding, ardently love programming." >>> a.swapcase() #交换大小写 "PYE EXTRAORDINARILY LOVE CODING, ARDENTLY LOVE PROGRAMMING."