大家好字符串是Python中使用频率最高的数据类型之一。无论是处理用户输入、解析文本文件还是生成日志信息都离不开它。这篇文章我们将系统性地学习字符串的七个核心方面每个部分都配有代码示例方便理解和查阅。一、定义字符串是由字符组成的序列用引号括起来表示。定义方式# 单引号 name 张三 # 双引号 city 北京 # 三引号支持多行 desc 这是一段 多行文本 可以换行写 # 三单引号同样支持多行 content 也是 多行文本空字符串empty1 empty2 empty3 str() # 使用 str() 构造方法单引号和双引号在功能上完全等价选择哪种主要看字符串内容是否包含引号# 字符串包含单引号外层用双引号 msg1 Im a student # 字符串包含双引号外层用单引号 msg2 他说你好 # 或者使用转义符 msg3 I\m a student二、转义转义字符用来表示一些特殊字符以反斜杠\开头。常用转义字符转义符含义\单引号\双引号\\反斜杠本身\n换行符\t制表符Tab键\r回车符\b退格符# 换行 print(第一行\n第二行) # 输出 # 第一行 # 第二行 # 制表符 print(姓名\t年龄\t城市) print(张三\t25\t北京) # 路径中的反斜杠需要转义 path C:\\Users\\Documents\\file.txt # 或者使用原始字符串推荐 path rC:\Users\Documents\file.txt原始字符串在字符串前加r可以使字符串中的反斜杠不被解释为转义字符# 普通字符串 s1 C:\new\test # \n 会被解释为换行 # 原始字符串 s2 rC:\new\test # 原样输出 C:\new\test原始字符串在写正则表达式、文件路径时非常实用。三、格式化方法格式化是指将变量值嵌入到字符串中Python提供了多种方式。1.%格式化旧式name 张三 age 25 print(我叫%s今年%d岁 % (name, age)) # 我叫张三今年25岁常用占位符%s字符串、%d整数、%f浮点数。2.format()方法name 张三 age 25 # 按位置 print(我叫{}今年{}岁.format(name, age)) # 按索引 print(我叫{1}今年{0}岁.format(age, name)) # 按变量名 print(我叫{name}今年{age}岁.format(namename, ageage))3. f-string推荐Python 3.6name 张三 age 25 print(f我叫{name}今年{age}岁) # 我叫张三今年25岁f-string 还可以嵌入表达式x, y 3, 5 print(f{x} {y} {x y}) # 3 5 8 price 12.345 print(f价格{price:.2f}元) # 价格12.35元f-string 是目前最推荐的格式化方式可读性最好性能也最高。四、索引字符串中的每个字符都有一个位置编号可以通过索引来访问。索引规则正向索引从0开始从左到右负向索引从-1开始从右到左s Python # 正向索引 print(s[0]) # P print(s[3]) # h print(s[5]) # n # 负向索引 print(s[-1]) # n print(s[-3]) # h索引对应关系字符Python正向012345负向-6-5-4-3-2-1索引越界使用索引时如果超出范围会报错s Python # print(s[10]) # IndexError: string index out of range字符串是不可变类型不能通过索引修改字符s Python # s[0] J # TypeError: str object does not support item assignment五、切片切片是从字符串中截取子串的操作语法为[start:end:step]。基本语法s Hello, World! # 截取一段 print(s[0:5]) # Hello 包含索引0不包含索引5 print(s[7:12]) # World 包含索引7不包含索引12 # 省略开始或结束 print(s[:5]) # Hello 从开头到索引4 print(s[7:]) # World! 从索引7到末尾 print(s[:]) # Hello, World! 全部 # 负索引切片 print(s[-6:-1]) # World 从倒数第6到倒数第2步长s abcdefghij print(s[::2]) # acegi 从开头到末尾每2个取1个 print(s[1::2]) # bdfhj 从索引1开始每2个取1个 print(s[::-1]) # jihgfedcba 反转字符串切片的特点左闭右开包含start不包含end容错性好索引超出范围不会报错只返回能取到的部分s abc print(s[0:10]) # abc 不会报错 print(s[10:20]) # 返回空字符串六、遍历遍历字符串的三种常用方式。1. 直接遍历字符s Python for char in s: print(char) # 输出P y t h o n 每行一个2. 通过索引遍历s Python for i in range(len(s)): print(s[i])3.enumerate()同时获取索引和值s Python for index, char in enumerate(s): print(f索引{index}{char}) # 索引0P # 索引1y # 索引2t # 索引3h # 索引4o # 索引5n4. 判断字符类型遍历时经常配合字符判断方法s Hello123 for char in s: if char.isdigit(): print(f{char} 是数字) elif char.isalpha(): print(f{char} 是字母)七、常用方法字符串提供了大量内置方法这里按功能分类整理。1. 大小写转换方法说明示例upper()全部转大写hello.upper()→HELLOlower()全部转小写HELLO.lower()→hellocapitalize()首字母大写hello.capitalize()→Hellotitle()每个单词首字母大写hello world.title()→Hello Worldswapcase()大小写互换Hello.swapcase()→hELLOtext python is FUN print(text.upper()) # PYTHON IS FUN print(text.lower()) # python is fun print(text.capitalize()) # Python is fun2. 去除空白方法说明strip()去除两端空白字符空格、换行、制表符lstrip()去除左端空白rstrip()去除右端空白text hello \n print(text.strip()) # hello print(text.lstrip()) # hello \n print(text.rstrip()) # hello也可以指定要去除的字符text !!!hello!!! print(text.strip(!)) # hello3. 查找与判断方法说明find(sub)返回第一个匹配的子串起始索引找不到返回 -1index(sub)与find相同但找不到会抛出异常rfind(sub)从右向左查找startswith(prefix)是否以指定前缀开头endswith(suffix)是否以指定后缀结尾count(sub)统计子串出现次数s hello world hello print(s.find(world)) # 6 print(s.find(python)) # -1 print(s.index(world)) # 6 # print(s.index(python)) # ValueError print(s.startswith(hello)) # True print(s.endswith(hello)) # True print(s.count(hello)) # 24. 拆分与拼接方法说明split(sep)按分隔符拆分成列表rsplit(sep)从右向左拆分splitlines()按换行符拆分join(iterable)将可迭代对象拼接成字符串# split data apple,banana,orange result data.split(,) print(result) # [apple, banana, orange] # split 可以指定最大拆分次数 data a,b,c,d print(data.split(,, 2)) # [a, b, c,d] # splitlines text 第一行\n第二行\n第三行 print(text.splitlines()) # [第一行, 第二行, 第三行] # join items [a, b, c] print(-.join(items)) # a-b-c5. 替换方法说明replace(old, new, count)替换子串可指定替换次数s hello world hello print(s.replace(hello, hi)) # hi world hi print(s.replace(hello, hi, 1)) # hi world hello6. 对齐与填充方法说明center(width, fillchar)居中ljust(width, fillchar)左对齐rjust(width, fillchar)右对齐zfill(width)右对齐用0填充s hello print(s.center(11, *)) # ***hello*** print(s.ljust(10, -)) # hello----- print(s.rjust(10, -)) # -----hello print(s.zfill(10)) # 00000hello7. 判断类型方法说明isalpha()是否全是字母isdigit()是否全是数字isalnum()是否全是字母或数字isspace()是否全是空白字符islower()是否全是小写isupper()是否全是大写istitle()是否符合标题格式print(hello.isalpha()) # True print(123.isdigit()) # True print(hello123.isalnum()) # True print( .isspace()) # True print(Hello.istitle()) # True八、总结字符串在Python中占据重要地位掌握好以下几个维度即可应对绝大多数场景知识点核心要点定义单引号、双引号、三引号转义\n、\t、\\原始字符串r格式化%、format()、f-string推荐索引正向从0开始负向从-1开始切片[start:end:step]左闭右开遍历for、range、enumerate()常用方法大小写、去空白、查找、拆分拼接、替换等字符串的各个方法不需要死记硬背多写代码自然就熟悉了。如果遇到不记得的方法可以用dir(str)查看所有方法或者用help(str.method)查看详细说明。如果觉得这篇内容对你有帮助欢迎收藏和分享。
Python 字符串完全指南:从基础到进阶操作
大家好字符串是Python中使用频率最高的数据类型之一。无论是处理用户输入、解析文本文件还是生成日志信息都离不开它。这篇文章我们将系统性地学习字符串的七个核心方面每个部分都配有代码示例方便理解和查阅。一、定义字符串是由字符组成的序列用引号括起来表示。定义方式# 单引号 name 张三 # 双引号 city 北京 # 三引号支持多行 desc 这是一段 多行文本 可以换行写 # 三单引号同样支持多行 content 也是 多行文本空字符串empty1 empty2 empty3 str() # 使用 str() 构造方法单引号和双引号在功能上完全等价选择哪种主要看字符串内容是否包含引号# 字符串包含单引号外层用双引号 msg1 Im a student # 字符串包含双引号外层用单引号 msg2 他说你好 # 或者使用转义符 msg3 I\m a student二、转义转义字符用来表示一些特殊字符以反斜杠\开头。常用转义字符转义符含义\单引号\双引号\\反斜杠本身\n换行符\t制表符Tab键\r回车符\b退格符# 换行 print(第一行\n第二行) # 输出 # 第一行 # 第二行 # 制表符 print(姓名\t年龄\t城市) print(张三\t25\t北京) # 路径中的反斜杠需要转义 path C:\\Users\\Documents\\file.txt # 或者使用原始字符串推荐 path rC:\Users\Documents\file.txt原始字符串在字符串前加r可以使字符串中的反斜杠不被解释为转义字符# 普通字符串 s1 C:\new\test # \n 会被解释为换行 # 原始字符串 s2 rC:\new\test # 原样输出 C:\new\test原始字符串在写正则表达式、文件路径时非常实用。三、格式化方法格式化是指将变量值嵌入到字符串中Python提供了多种方式。1.%格式化旧式name 张三 age 25 print(我叫%s今年%d岁 % (name, age)) # 我叫张三今年25岁常用占位符%s字符串、%d整数、%f浮点数。2.format()方法name 张三 age 25 # 按位置 print(我叫{}今年{}岁.format(name, age)) # 按索引 print(我叫{1}今年{0}岁.format(age, name)) # 按变量名 print(我叫{name}今年{age}岁.format(namename, ageage))3. f-string推荐Python 3.6name 张三 age 25 print(f我叫{name}今年{age}岁) # 我叫张三今年25岁f-string 还可以嵌入表达式x, y 3, 5 print(f{x} {y} {x y}) # 3 5 8 price 12.345 print(f价格{price:.2f}元) # 价格12.35元f-string 是目前最推荐的格式化方式可读性最好性能也最高。四、索引字符串中的每个字符都有一个位置编号可以通过索引来访问。索引规则正向索引从0开始从左到右负向索引从-1开始从右到左s Python # 正向索引 print(s[0]) # P print(s[3]) # h print(s[5]) # n # 负向索引 print(s[-1]) # n print(s[-3]) # h索引对应关系字符Python正向012345负向-6-5-4-3-2-1索引越界使用索引时如果超出范围会报错s Python # print(s[10]) # IndexError: string index out of range字符串是不可变类型不能通过索引修改字符s Python # s[0] J # TypeError: str object does not support item assignment五、切片切片是从字符串中截取子串的操作语法为[start:end:step]。基本语法s Hello, World! # 截取一段 print(s[0:5]) # Hello 包含索引0不包含索引5 print(s[7:12]) # World 包含索引7不包含索引12 # 省略开始或结束 print(s[:5]) # Hello 从开头到索引4 print(s[7:]) # World! 从索引7到末尾 print(s[:]) # Hello, World! 全部 # 负索引切片 print(s[-6:-1]) # World 从倒数第6到倒数第2步长s abcdefghij print(s[::2]) # acegi 从开头到末尾每2个取1个 print(s[1::2]) # bdfhj 从索引1开始每2个取1个 print(s[::-1]) # jihgfedcba 反转字符串切片的特点左闭右开包含start不包含end容错性好索引超出范围不会报错只返回能取到的部分s abc print(s[0:10]) # abc 不会报错 print(s[10:20]) # 返回空字符串六、遍历遍历字符串的三种常用方式。1. 直接遍历字符s Python for char in s: print(char) # 输出P y t h o n 每行一个2. 通过索引遍历s Python for i in range(len(s)): print(s[i])3.enumerate()同时获取索引和值s Python for index, char in enumerate(s): print(f索引{index}{char}) # 索引0P # 索引1y # 索引2t # 索引3h # 索引4o # 索引5n4. 判断字符类型遍历时经常配合字符判断方法s Hello123 for char in s: if char.isdigit(): print(f{char} 是数字) elif char.isalpha(): print(f{char} 是字母)七、常用方法字符串提供了大量内置方法这里按功能分类整理。1. 大小写转换方法说明示例upper()全部转大写hello.upper()→HELLOlower()全部转小写HELLO.lower()→hellocapitalize()首字母大写hello.capitalize()→Hellotitle()每个单词首字母大写hello world.title()→Hello Worldswapcase()大小写互换Hello.swapcase()→hELLOtext python is FUN print(text.upper()) # PYTHON IS FUN print(text.lower()) # python is fun print(text.capitalize()) # Python is fun2. 去除空白方法说明strip()去除两端空白字符空格、换行、制表符lstrip()去除左端空白rstrip()去除右端空白text hello \n print(text.strip()) # hello print(text.lstrip()) # hello \n print(text.rstrip()) # hello也可以指定要去除的字符text !!!hello!!! print(text.strip(!)) # hello3. 查找与判断方法说明find(sub)返回第一个匹配的子串起始索引找不到返回 -1index(sub)与find相同但找不到会抛出异常rfind(sub)从右向左查找startswith(prefix)是否以指定前缀开头endswith(suffix)是否以指定后缀结尾count(sub)统计子串出现次数s hello world hello print(s.find(world)) # 6 print(s.find(python)) # -1 print(s.index(world)) # 6 # print(s.index(python)) # ValueError print(s.startswith(hello)) # True print(s.endswith(hello)) # True print(s.count(hello)) # 24. 拆分与拼接方法说明split(sep)按分隔符拆分成列表rsplit(sep)从右向左拆分splitlines()按换行符拆分join(iterable)将可迭代对象拼接成字符串# split data apple,banana,orange result data.split(,) print(result) # [apple, banana, orange] # split 可以指定最大拆分次数 data a,b,c,d print(data.split(,, 2)) # [a, b, c,d] # splitlines text 第一行\n第二行\n第三行 print(text.splitlines()) # [第一行, 第二行, 第三行] # join items [a, b, c] print(-.join(items)) # a-b-c5. 替换方法说明replace(old, new, count)替换子串可指定替换次数s hello world hello print(s.replace(hello, hi)) # hi world hi print(s.replace(hello, hi, 1)) # hi world hello6. 对齐与填充方法说明center(width, fillchar)居中ljust(width, fillchar)左对齐rjust(width, fillchar)右对齐zfill(width)右对齐用0填充s hello print(s.center(11, *)) # ***hello*** print(s.ljust(10, -)) # hello----- print(s.rjust(10, -)) # -----hello print(s.zfill(10)) # 00000hello7. 判断类型方法说明isalpha()是否全是字母isdigit()是否全是数字isalnum()是否全是字母或数字isspace()是否全是空白字符islower()是否全是小写isupper()是否全是大写istitle()是否符合标题格式print(hello.isalpha()) # True print(123.isdigit()) # True print(hello123.isalnum()) # True print( .isspace()) # True print(Hello.istitle()) # True八、总结字符串在Python中占据重要地位掌握好以下几个维度即可应对绝大多数场景知识点核心要点定义单引号、双引号、三引号转义\n、\t、\\原始字符串r格式化%、format()、f-string推荐索引正向从0开始负向从-1开始切片[start:end:step]左闭右开遍历for、range、enumerate()常用方法大小写、去空白、查找、拆分拼接、替换等字符串的各个方法不需要死记硬背多写代码自然就熟悉了。如果遇到不记得的方法可以用dir(str)查看所有方法或者用help(str.method)查看详细说明。如果觉得这篇内容对你有帮助欢迎收藏和分享。