目录
- 专栏列表
- 前言
- 1. 字符串基础
- 2. 字符串方法
- 字符串查询
- 字符串修改
- 字符串切片
- 3. 字符串格式化
- 旧式格式化(`%` 操作符)
- `str.format()` 方法
- f-string(Python 3.6+)
- 4. 字符串编码
- 5. Unicode 和 ASCII
- 6. 正则表达式
- 7. 字符串比较
- 8. 字符串连接
- 9. 字符串不可变性
- 10. 字符串的内存视图
- 总结
在前两篇教程中,我们学习了 Python 的基本语法和数据结构。本篇教程,我们将深入探讨 Python 中的字符串特性大全
专栏列表
- Python教程(一):环境搭建及PyCharm安装
- Python 教程(二):语法与数据结构
- Python 教程(三):字符串特性大全

正文开始,如果觉得文章对您有帮助,请帮我三连+订阅,谢谢💖💖💖
前言
Python 3 中的字符串处理功能非常强大,提供了丰富的方法和操作来处理文本数据。下面我们将介绍 字符串的 基本操作、字符串方法、格式化、编码等等功能。
1. 字符串基础
字符串是 Python 中的一种不可变数据类型,用于存储文本数据。
- 创建字符串:可以使用单引号或双引号来创建字符串。
- 访问字符:通过索引访问字符串中的字符,索引从 0 开始。
s = "Hello, World!"
print(s[0]) # 输出: H
print(s[7]) # 输出: W

2. 字符串方法
Python 字符串对象提供了许多有用的方法,用于字符串的查询、修改和处理。
字符串查询
str.find(sub):返回子字符串sub在字符串中首次出现的索引。str.index(sub):类似于find(),但如果子字符串不存在则抛出ValueError。str.count(sub):返回子字符串在字符串中出现的次数。str.startswith(prefix):检查字符串是否以指定的前缀开始。str.endswith(suffix):检查字符串是否以指定的后缀结束。
s = "Hello, World!"
print(s.find('o'))
print(s.index('o'))
print(s.count('o'))
print(s.startswith('o'))
print(s.endswith('o'))

字符串修改
str.upper():将字符串中的所有字符转换为大写。str.lower():将字符串中的所有字符转换为小写。str.strip():移除字符串两端的空白字符。str.replace(old, new):替换字符串中的旧子字符串为新子字符串。
s = "Hello, World!"
print(s.upper())
print(s.lower())
print(s.strip())
print(s.replace('o','K'))

字符串切片
str[start:end]:获取字符串从索引start到end-1的子字符串。str[start:]:获取字符串从索引start到末尾的子字符串。str[:end]:获取字符串从开始到索引end-1的子字符串。
s = "Hello, World!"
print(s[1:2])
print(s[1:])
print(s[:2])

3. 字符串格式化
Python 3 提供了多种字符串格式化的方法。
旧式格式化(% 操作符)
name = "张胜男"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
# Hello, 张胜男. You are 30 years old.
str.format() 方法
name = "张胜男"
age = 30
print("Hello, {}. You are {} years old.".format(name, age))
f-string(Python 3.6+)
name = "张胜男"
age = 30
print(f"Hello, {name}. You are {age} years old.")
4. 字符串编码
字符串可以编码为字节序列,反之亦然。
str.encode(encoding='utf-8'):将字符串编码为字节序列。bytes.decode(encoding='utf-8'):将字节序列解码为字符串。
s = "Hello, World!"
encoded = s.encode('utf-8')
print(encoded) # 输出: b'Hello, World!'
decoded = encoded.decode('utf-8')
print(decoded) # 输出: Hello, World!
5. Unicode 和 ASCII
Python 3 默认使用 Unicode,可以处理多种语言的字符。
ord(char):获取单个字符的 Unicode 编码。chr(i):将 Unicode 编码转换为对应的字符。
print(ord('A')) # 输出: 65
print(chr(65)) # 输出: A
6. 正则表达式
Python 的 re 模块提供了正则表达式的支持,用于复杂的字符串匹配和处理。
import re
pattern = r"\d+"
result = re.findall(pattern, "有123个苹果和456个橙子")
print(result) # 输出: ['123', '456']
7. 字符串比较
字符串比较是大小写敏感的。
s1 = "hello"
s2 = "Hello"
print(s1 == s2) # 输出: False
8. 字符串连接
可以使用 + 操作符连接字符串。
s1 = "Hello, "
s2 = "World!"
s3 = s1 + s2
print(s3) # 输出: Hello, World!
9. 字符串不可变性
字符串是不可变的数据类型,这意味着一旦创建就不能更改。
s = "Hello"
s[0] = "h" # TypeError: 'str' object does not support item assignment
10. 字符串的内存视图
可以使用 bytes 和 bytearray 来处理二进制数据。
b = bytes([72, 101, 108, 108, 111]) # 等价于 b'Hello'
ba = bytearray(b)
ba[0] = 104 # 修改第一个字符为 'h'
print(ba) # 输出: bytearray(b'helli')
总结
Python 3 提供了非常丰富的字符串处理功能,从基本的字符串操作到复杂的字符串格式化和正则表达式处理。掌握这些字符串处理技巧可以极大地提高你的编程效率和灵活性。希望这个梳理能帮助你更好地理解和使用 Python 3 的字符串处理功能。如果你有任何问题或需要进一步的帮助,请随时联系我们。



















