【python】字符串 📅 发布时间:2026/9/1 20:07:20 👁 浏览次数: 字符串反斜杠\字符串换行a hello \ world\ 是续行符只是代码上换行字符串本身还是一行等价于 hello world单引号 、双引号 区别如果字符串里面有单引号 外层优先用双引号不用转义c Im TOM转义字符\c Im Tom d I\m Tom如果外层是单引号内部又要写单引号必须转义 \三引号 / 保存多行文本字符串内可以直接换行输出也会保留换行注意三引号形式的字符串支持换行f I am TOM print(f)字符串输出# nameTom # print(我的名字%s%name) # print(f我的名字是{name})字符串输入#字符串输入 # nameinput(请输入你的名字) # print(f你输入的名字是{name}) # # passwordinput(请输入你的密码) # print(f你输入的密码是{password})下标索引 (下标)字符串中每一个字符都会分配一个编号通过编号就能取出对应的字符str1abcdefg print(str1[1]) #b print(str1[2]) #c print(str1[3]) #d字符数据从0开始顺序分配一个编号,使用这个编号精确找到某个字符数据---下标或索引注意下标从 0 开始字符串切片切片语法序列[开始位置下标:结束位置下标:步长]规则取左不取右包含起始不包含结束注意:a不包含结束位置下标对应的数据正负整数均可b步长是选取间隔正负整数均可默认步长为 1str1abcdefg print(str1[0:3]) # abc 取012 print(str1[2:]) #从索引2取到最后 cdefg print(str1[:4]) #从头索引到3 abcd print(str1[: : -1]) #字符串反转 gfedcbanameabcdefg print(name[2:5:1]) #开始下标2 结束下标为5 但不包含结束下标 步长为1 cde print(name[2:5]) #同上默认步长为1 cde print(name[:5]) print(name[2:]) #忽略结束下标从下标2取到字符串最后 print(name[:]) #忽略起始下标和结束下标截取整个字符串 print(name[::2]) #从头到尾步长为2 print(name[:-1]) #从头截取到最后一个字符之前不包括最后一个字符 print(name[-4:-1]) #从倒数第4尾取到倒数第一位 print(name[::-1]) #步长为-1 字符串反转倒序输出常用操作方法查找find查找子串找到返回起始下标找不到返回 -1不会报错语法字符串序列.find(子串, 开始下标, 结束下标)起始、结束下标可省略 → 全字符串查找mystr hello world and itcast and itheima and Python print(mystr.find(and)) # 12 print(mystr.find(and, 15, 30)) # 23 print(mystr.find(ands)) # -1ands不存在index()查找子串找到返回起始下标找不到直接报异常报错语法字符串序列.index(子串, 开始下标, 结束下标)mystr hello world and itcast and itheima and Python print(mystr.index(and)) # 12 print(mystr.index(and, 15, 30)) # 23 print(mystr.index(ands)) # 报错 ValueErrorrfind() / rindex()rfind()和find()一样从右往左查找找不到返回‑1rindex()和index()一样从右往左查找找不到报错count()统计子串出现次数找不到返回 0mystrhello world print(mystr.count(l))语法字符串序列.count(子串, 开始下标, 结束下标)修改replace()— 字符串替换a语法字符串序列.replace(旧子串, 新子串, 替换次数)1.替换次数超过子串出现次数则全部替换2.原字符串不会被修改bmystrhello world and itcast and itheima and Python print(mystr.replace(and,he)) #hello world he itcast he itheima he Python print(mystr) #替换后的字符串原字符串不会被修改 print(mystr.replace(and,he,1)) # #hello world he itcast and itheima and Python # 当替换次数大于旧字符串个数时旧字符串个数全部会被新字符串替换 print(mystr.replace(and,he,10))split() — 分割字符串返回列表a语法字符串序列.split(分割字符, num)1. num分割次数返回列表元素个数 num12. 分割字符会丢失不会出现在结果里b# mystrhello world and itcast and itheima and Python # print(mystr.split(and)) # # [hello world , itcast , itheima , Python] # # print(mystr.split(and,2)) # # [hello world , itcast , itheima and Python] # # print(mystr.split( )) # # [hello, world, and, itcast, and, itheima, and, Python] # # print(mystr.split( ,2)) # 分割字符分割次数 # #[hello, world, and itcast and itheima and Python]join() — 合并序列为字符串分割的逆操作a语法连接符.join(多字符串组成的序列)blist1[chuan,zhi,bo,ke] t1(aa,b,cc,ddd) print(_.join(list1)) # chuan_zhi_bo_ke print(....join(t1)) # aa...b...cc...ddd大小写转换acapitalize()首字符大写其余全部小写bc