字符串功能的详细教学 一。字符串基础# 1. 字符串的声明# s1 hello world# s2 hello world# # 三引号: 格式化字符串# s3 hello world# s4 # hello# world# ## print(type(s1), type(s2), type(s3), type(s4))# print(s4)# 2. 转义字符# msg 123qwe-*/#%……*、# print(msg)# msg2 123qwe-*/#%……*、# print(msg)## msg3 123\q\\\\\\\we-*/#%……*、# print(msg3)## msg4 hello\nworld\thi world# print(msg4)## msg5 C:\\Program Files\\Python313\\new# print(msg5)## msg6 rC:\Users\Administrator\AppData\Roaming\npm\node_modules\obfuscator-io-deobfuscator\node_modules\jridgewell\gen-mapping\dist\types# print(msg6)nameqikuage1addr东三街print(名字叫,name,年纪是,age,地址是,addr,sep)# 使用fprint(f名字叫{name}年纪是{age}地址是{addr})# 使用%连接print(名字叫%s年纪是%s地址是%s%(name,age,addr))# 使用format函数print(名字叫{}年纪是{}地址是{}.format(name,age,addr))二。索引与切片 1. 索引与遍历 2. 切片 # msg 中华人民共和国台湾省# print(len(msg)) # length# print(msg[0], msg[9])# 遍历方式1# for e in msg:# print(e)# 遍历方式2 先通过range结合len 拿到每一个字符对应的索引# for i in range(len(msg)):# print(i, msg[i])# # 有一个字符串 abcdcba abcddcba 123454321 12345421 如何确定该字符串是否对称# s 12345421# # s[0] s[6]# # s[1] s[5]# # s[2] s[4]# # s[3] s[3]# # s[4] s[2]## for i in range(len(s) // 2):# if s[i] ! s[len(s) - 1 - i]:# print(f字符{s[i]}与字符{s[len(s) - 1 - i]}不一致退出)# break# else:# print(f是对称字符串)# msg 中华人民共和国台湾省# print(len(msg)) # length# print(msg[0], msg[9])## # print(msg[-1], msg[-10])## # start:stop:step 从start(包含)开始 到stop(不包含)结束 step步长# print(msg[7:])# print(msg[:7])# print(msg[2:7])# print(msg[2:7:2])## print(msg[-3:-1:1])## print(msg[7:2:-1])# print(msg[::-1])三.字符串的操作# 返回子字符对应的索引 找不到会报错print(hello world.index(llo,))print(hello world.rindex(l,))ifll0inhello world:print(hello world.index(ll0))else:print(f非子字符串)# 返回子字符对应的索引 找不到会返回-1print(hello world.find(llo))print(hello world.find(ll0))print(hello world.find(l,4,5))print(hello world.rfind(l))# 计子字符串出现的次数 没有出现返回0print(hello world.count(l,4))# 转小写print(heLlo WorlD.lower())# 转大写print(heLlo WorlD.upper())# 单词首字母大写print(heLlo worlD.title())# 首字母大写print(heLlo worlD.capitalize())# 大小写转换print(heLlo worlD.swapcase())# 对齐# 居中print(hello world.center(20))print(hello world.center(20,*))# 居左print(hello world.ljust(20,*))# 居右print(hello world.rjust(20,*))# 居右 左侧填0print(hello world.zfill(20))# 开始结尾print( hello world .startswith( ))print( hello world .endswith( ))# 剔除空白print( hello world .strip())print(hello world.strip())print(hello world.lstrip())print(hello world.rstrip())# 拼接print(.join(hello world))print( .join([hello,world]))# 切割 默认空格print(hello world.split())print(hello world.split(l))# 替换 count 指明替换次数print(hello world hello china.replace(hello,hi,1))# bytes 字符串前有字符 bprint(hello world 123 中国.encode(gbk))# 解码print(bhello world 123 \xd6\xd0\xb9\xfa.decode(gbk))# is*print(az.isalpha())print(19.isdigit())print(19az.isalnum())print(Az.islower())print(Az.isupper())print(Az Bz.istitle())