字符串是Python开发中接触最频繁的数据类型之一,无论是清洗用户输入、解析日志文件,还是拼接SQL条件,都离不开对字符串的灵活操作。本文按照实际使用频率,系统梳理字符串的定义、转义、格式化、索引切片、遍历以及常用内置方法,并给出可直接运行的代码示例。
一、字符串的几种定义方式
字符串本质上是字符的有序序列,使用引号包裹即可创建。单引号和双引号在功能上完全等价,选择依据主要是字符串内容是否包含引号;三引号则用于多行文本。
- # 单引号
- name = '张三'
- # 双引号
- city = "北京"
- # 三引号支持换行
- desc = """这是一个
- 多行字符串"""
- content = '''同样支持
- 多行文本'''
- # 空字符串的三种写法
- empty1 = ""
- empty2 = ''
- empty3 = str()
复制代码
如果字符串内部包含单引号,外层就用双引号;反之同理。也可以统一用反斜杠转义,但可读性稍差。
- msg1 = "I'm a student"
- msg2 = '他说:"你好"'
- msg3 = 'I\'m a student'
复制代码
二、转义字符与原始字符串
反斜杠在字符串中承担转义职责,常见的转义符包括:\' 表示单引号,\" 表示双引号,\\ 表示反斜杠本身,\n 换行,\t 制表符,\r 回车,\b 退格。
- print("第一行\n第二行")
- print("姓名\t年龄\t城市")
- print("张三\t25\t北京")
复制代码
写Windows路径时,反斜杠容易和转义符冲突。比如 "C:\new\test" 里的 \n 会被当成换行。解决办法是使用原始字符串,在引号前加 r:
原始字符串在正则表达式和文件路径场景中非常实用,能省去大量双反斜杠的书写。
三、字符串格式化的三种方式
1. % 格式化(旧式)
- name = "张三"
- age = 25
- print("我叫%s,今年%d岁" % (name, age))
复制代码
%s 对应字符串,%d 对应整数,%f 对应浮点数。
2. format() 方法
支持位置参数、索引参数和变量名参数:
- print("我叫{},今年{}岁".format(name, age))
- print("我叫{1},今年{0}岁".format(age, name))
- print("我叫{name},今年{age}岁".format(name=name, age=age))
复制代码
3. f-string(Python 3.6+)
f-string 是当前最推荐的方式,可读性最好、性能也最高。花括号内可以直接写变量名或表达式:
- x, y = 3, 5
- print(f"{x} + {y} = {x + y}")
- price = 12.345
- print(f"价格:{price:.2f}元")
复制代码
四、索引规则与常见陷阱
字符串中的每个字符都有位置编号,正向索引从0开始,负向索引从 -1 开始。以 "Python" 为例:
- s = "Python"
- print(s[0]) # P
- print(s[3]) # h
- print(s[-1]) # n
- print(s[-3]) # h
复制代码
索引对应关系:
字符 P y t h o n
正向 0 1 2 3 4 5
负向 -6 -5 -4 -3 -2 -1
两个需要特别注意的点:
1. 索引越界会抛出 IndexError,所以在动态取字符时要注意长度判断。
2. 字符串是不可变对象,不能通过索引直接修改字符:s[0] = "J" 会报 TypeError。
五、切片操作语法与步长
切片是从字符串中截取子串的最直接方式,语法为 [start:end:step],遵循左闭右开规则,即包含 start 位置,不包含 end 位置。
- s = "Hello, World!"
- print(s[0:5]) # Hello
- print(s[7:12]) # World
- print(s[:5]) # Hello
- print(s[7:]) # World!
- print(s[:]) # 整个字符串
- print(s[-6:-1]) # World
复制代码
步长的典型用法包括间隔取值和反转字符串:
- s = "abcdefghij"
- print(s[::2]) # acegi
- print(s[1::2]) # bdfhj
- print(s[::-1]) # jihgfedcba
复制代码
切片比索引容错性强得多:即使 end 超过字符串长度也不会报错,最多返回空字符串。例如 s = "abc",s[0:10] 返回 "abc",s[10:20] 返回 ""。
六、遍历字符串的四种姿势
1. 直接遍历字符:
- for char in "Python":
- print(char)
复制代码
2. 通过索引遍历:
- s = "Python"
- for i in range(len(s)):
- print(s[i])
复制代码
3. 使用 enumerate 同时拿到索引和值:
- for index, char in enumerate("Python"):
- print(f"索引{index}:{char}")
复制代码
4. 遍历时判断字符类型,可结合 isdigit 和 isalpha 等判断方法:
- s = "Hello123"
- for char in s:
- if char.isdigit():
- print(f"{char} 是数字")
- elif char.isalpha():
- print(f"{char} 是字母")
复制代码
七、高频内置方法分类整理
1. 大小写转换
- text = "python is FUN"
- print(text.upper()) # PYTHON IS FUN
- print(text.lower()) # python is fun
- print(text.capitalize()) # Python is fun
- print(text.title()) # Python Is Fun
- print(text.swapcase()) # PYTHON IS fun
复制代码
2. 去除空白字符
strip() 去除两端空白,lstrip() 只去左侧,rstrip() 只去右侧。空白包括空格、换行、制表符。
- text = " hello \n"
- print(text.strip()) # hello
- print(text.lstrip()) # hello \n
- print(text.rstrip()) # hello
复制代码
strip 也能指定要去除的字符:
- text = "!!!hello!!!"
- print(text.strip("!")) # hello
复制代码
3. 查找与判断
find 找不到时返回 -1,index 找不到会抛 ValueError;rfind 从右向左查找;startswith/endswith 判断前后缀;count 统计出现次数。
- s = "hello world hello"
- print(s.find("world")) # 6
- print(s.find("python")) # -1
- print(s.index("world")) # 6
- print(s.startswith("hello")) # True
- print(s.endswith("hello")) # True
- print(s.count("hello")) # 2
复制代码
4. 拆分与拼接
split 按指定分隔符拆成列表,可以加第二个参数限制最大拆分次数;splitlines 按换行符拆分;join 则用于将可迭代对象拼接成字符串。
- data = "apple,banana,orange"
- print(data.split(",")) # ['apple', 'banana', 'orange']
- data = "a,b,c,d"
- print(data.split(",", 2)) # ['a', 'b', 'c,d']
- text = "第一行\n第二行\n第三行"
- print(text.splitlines()) # ['第一行', '第二行', '第三行']
- items = ['a', 'b', 'c']
- print("-".join(items)) # a-b-c
复制代码
5. 替换
replace 支持指定替换次数,默认替换全部。
- s = "hello world hello"
- print(s.replace("hello", "hi")) # hi world hi
- print(s.replace("hello", "hi", 1)) # hi world hello
复制代码
6. 对齐与填充
center、ljust、rjust 分别实现居中、左对齐、右对齐,可以指定填充字符;zfill 是右对齐并用 0 填充,常用于数字补零。
- s = "hello"
- print(s.center(11, "*")) # ***hello***
- print(s.ljust(10, "-")) # hello-----
- print(s.rjust(10, "-")) # -----hello
- print(s.zfill(10)) # 00000hello
复制代码
7. 判断类型
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
复制代码
八、记忆要点
字符串相关知识可以按定义、转义、格式化、索引、切片、遍历、常用方法这七个维度去掌握。日常开发中,格式化优先使用 f-string,路径和正则用原始字符串 r"",切片注意左闭右开,查找时如果不需要异常就用 find 而不是 index。
方法记不住也没关系,Python 提供了内置帮助接口:
- dir(str)
- help(str.replace)
复制代码
多写几遍代码,这些操作自然会形成肌肉记忆。 |