Python字符串知识点总结
1. 字符串基础
- 字符串是不可变的序列类型
- 可以用单引号(')、双引号(")或三引号('''或""")创建
- 三引号用于多行字符串
s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''
2. 字符串操作
2.1 拼接
s = 'hello' + ' ' + 'world' # 'hello world'
2.2 重复
s = 'hi' * 3 # 'hihihi'
2.3 索引和切片
s = 'Python'
print(s[0]) # 'P' (第一个字符)
print(s[-1]) # 'n' (最后一个字符)
print(s[1:4]) # 'yth' (切片)
print(s[:3]) # 'Pyt' (从开始到索引2)
print(s[3:]) # 'hon' (从索引3到结束)
print(s[::2]) # 'Pto' (步长为2)
3. 字符串方法
3.1 大小写转换
s = 'Hello World'
print(s.lower()) # 'hello world'
print(s.upper()) # 'HELLO WORLD'
print(s.capitalize()) # 'Hello world'
print(s.title()) # 'Hello World'
print(s.swapcase()) # 'hELLO wORLD'
3.2 查找和替换
s = 'hello world'
print(s.find('lo')) # 3 (返回索引,找不到返回-1)
print(s.index('lo')) # 3 (类似find,但找不到会报错)
print(s.rfind('l')) # 9 (从右开始查找)
print(s.replace('l', 'L')) # 'heLLo worLd'
3.3 分割和连接
s = 'a,b,c,d'
print(s.split(',')) # ['a', 'b', 'c', 'd']
print(' '.join(['a', 'b', 'c'])) # 'a b c'
print(s.partition(',')) # ('a', ',', 'b,c,d')
3.4 去除空白
s = ' hello '
print(s.strip()) # 'hello'
print(s.lstrip()) # 'hello '
print(s.rstrip()) # ' hello'
3.5 判断方法
s = '123abc'
print(s.isdigit()) # False (是否全数字)
print(s.isalpha()) # False (是否全字母)
print(s.isalnum()) # True (是否字母或数字)
print(s.islower()) # True (是否全小写)
print(s.isupper()) # False (是否全大写)
print(s.isspace()) # False (是否全空白字符)
print(s.startswith('123')) # True
print(s.endswith('abc')) # True
3.6 格式化
name = 'Alice'
age = 25
# 旧式格式化
print('My name is %s and I am %d years old.' % (name, age))
# format方法
print('My name is {} and I am {} years old.'.format(name, age))
# f-string (Python 3.6+)
print(f'My name is {name} and I am {age} years old.')
4. 字符串编码
- Python 3中字符串默认是Unicode (utf-8)
- 编码解码操作:
s = '你好'
b = s.encode('utf-8') # 编码为bytes
s2 = b.decode('utf-8') # 解码回字符串
5. 原始字符串
path = r'C:\new\folder' # 实际字符串是 C:\new\folder
6. 字符串常量
import string
print(string.ascii_letters) # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(string.digits) # '0123456789'
print(string.punctuation) # 所有标点符号
print(string.whitespace) # 所有空白字符
7. 其他有用方法
s = 'hello'
print(len(s)) # 5 (长度)
print('e' in s) # True (成员检查)
print(s.count('l')) # 2 (计数)
print(s.center(10, '-')) # '--hello---' (居中)
print(s.zfill(10)) # '00000hello' (填充0)
8. 字符串与字节串
- str类型表示Unicode字符串
- bytes类型表示二进制数据
- 两者可以互相转换,但需要指定编码方式
text = "你好"
data = text.encode('utf-8') # str -> bytes
text2 = data.decode('utf-8') # bytes -> str