
1. 定义在Python中字符串由单引号、双引号或三引号或包围的字符序列组成。gs1 Hello s2 World s3 多行 字符串2. 转义反斜杠\用于转义特殊字符如换行符、引号等常见转义字符\n换行、\t制表符、\\反斜杠本身等# \n,换行\t缩进 # 如\,\等使引号失去原本的意义 # \\ 转义转义字符 msg 13143safdaf\fed print(msg) msg1 hello\nword msg2 dsaf||\dasdfda msg4 dasdh\\sdh # 声明rdfgae\dsa\32\fda表示字符串中的所有字符均保留原始意义 msg3 rC:\Program Files\XMind\resources\app.asar.unpacked\node_modules\acorn\bin print(msg2, \n, msg3)3. 格式化方法1使用f-stringname CSDN age 25 print(f名字叫{name}年纪是{age})2使用%连接name CSDN age 25 print(名字叫%s年纪是%s % (name, age))3使用format()方法name CSDN age 25 print(名字叫{}年纪是{}.format(name, age))4. 索引字符串的索引值是从0开始的获取第几个字符索引值一般为该数减一s Python char s[0] # 获取第1个字符P char1 s[2] # 获取第3个字符t5. 切片字符串的切片获取索引start是可以去取到的stop值是不能够取到的step值默认为1当start值大于stop值时step值必须写并且为负值s Python substring s[1:4] # 切片获取索引1到3的子串yth substring s[4:0:-1] # 切片获取索引1到3的子串ohty6. 遍历字符串可通过循环或者索引遍历s Python for char in Python: print(char) for i in range(len(s)): print(s[i])7. 常用方法1大小写转换# 转小写 print(heLlo WorlD.lower()) # 转大写 print(heLlo WorlD.upper()) # 单词首字母大写 print(heLlo worlD.title()) # 首字母大写 print(heLlo worlD.capitalize()) # 大小写转换 print(heLlo worlD.swapcase())2去除空白字符# 剔除空白 print( hello world .strip()) print(hello world.strip()) print(hello world.lstrip()) print(hello world.rstrip())3返回子字符对应的索引 找不到会报错print(hello world.index(llo,)) print(hello world.rindex(l,)) if ll0 in hello world: print(hello world.index(ll0)) else: print(f非子字符串)4返回子字符对应的索引 找不到会返回-1print(hello world.find(llo)) print(hello world.find(ll0)) print(hello world.find(l, 4, 5)) print(hello world.rfind(l))5计子字符串出现的次数 没有出现返回0print(hello world.count(l, 4))6对齐# 居中 print(hello world.center(20)) print(hello world.center(20, *)) # 居左 print(hello world.ljust(20, *)) # 居右 print(hello world.rjust(20, *)) # 居右 左侧填0 print(hello world.zfill(20))7拼接print(.join(hello world)) print( .join([hello, world]))