Python中的字符串 在 Python 开发、数据分析、算法刷题中字符串、列表、元组、字典、集合是最基础、使用频率最高的 5 种内置数据结构。str字符串是不可变序列(定义后无法直接修改内部字符修改操作会生成新字符串)有序、可索引、可切片、支持遍历可以使用 , , 进行定义使用三引号时可以填入多行文本基础创建与取值定义字符串# 创建 s1 python s2 666 s3 字符串 索引正向从0反向从-1print(s1[0]) print(s1[-1])切片[起始 结束取不到 步长]左闭右开print(s1[1:4]) print(s1[::-1])内置方法大小写转换#转小写 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, *)) # 在字符串左侧补 0把字符串扩充到指定总长度 print(hello world.zfill(20, ))开始结尾#使用Hi 替换掉Hello s.replace(Hello, Hi) # 按指定分割符将字符串分割为为列表 s.split( ) -.join([a,b,c]) # a-b-c去除空白#strip()函数可以指定删除字符 print( hello world .strip()) print(hello world.strip()) #从左开始删除直到遇见字符串 print(hello world.lstrip()) #从右开始删除直到遇见字符串 print(hello world.rstrip())拼接print(.join(hello world)) print(.join([1,2,3,4,5]))切割print(hello world.split()) print(hello world.split(l))替换 count 指明替换次数print(hello world hello china.replace(hello, hi, 1))bytes 字符串前有字符b二进制编码字符串print(hello world 123 中国.encode(utf8))解码print(bhello world.decode(utf8)) print(bhello world 123 \xe4\xb8\xad\xe5\x9b\xbd.decode(utf8))