Python字符串基础
·
字符串 —— 不可变的字符序列
核心特点
-
不可变:一旦创建,内容无法修改;任何“修改”操作都会返回新字符串。
-
有序序列:支持索引(
s[i])和切片(s[start:end:step]),可遍历。 -
Unicode 支持:Python 3 字符串是 Unicode 字符序列,支持中文、emoji 等多语言字符。
-
高效拼接:少量字符串可用
+,大量拼接推荐''.join(),性能远优于循环加。 -
灵活格式化:支持
%传统格式、str.format()以及最推荐的 f-string(Python 3.6+)。
常用操作与方法分类
下面以 s = " Hello, Python! " 为例(注意首尾空格)。
1. 大小写转换
s.upper() # ' HELLO, PYTHON! ' 全部大写 s.lower() # ' hello, python! ' 全部小写 s.capitalize() # ' hello, python! ' 首字符大写(注意空格影响) s.title() # ' Hello, Python! ' 每个单词首字母大写 s.swapcase() # ' hELLO, pYTHON! ' 大小写反转 s.casefold() # 更彻底的小写,用于不区分大小写的匹配
2. 查找与替换
s.find('Py') # 8 返回第一次出现的索引,未找到返回 -1
s.rfind('o') # 12 从右侧查找
s.index('Py') # 8 与 find 类似,但未找到会报 ValueError
s.rindex('o') # 12
s.count('o') # 2 统计子串出现次数
s.replace('Python', 'World') # ' Hello, World! ' 替换所有匹配
# 可指定最大替换次数: s.replace('o', '0', 1)
3. 判断内容类型(返回布尔值)
s.startswith(' He') # True 注意含空格
s.endswith('! ') # True
'abc123'.isalnum() # True 是否全是字母或数字
'abc'.isalpha() # True 是否全是字母
'123'.isdigit() # True 是否全是数字
' '.isspace() # True 是否全是空白字符
'Hello'.islower() # False 是否全是小写
'HELLO'.isupper() # True 是否全是大写
'Hello World'.istitle() # True 是否每个单词首字母大写
4. 去除空白或指定字符
s.strip() # 'Hello, Python!' 去除两端空白
s.lstrip() # 'Hello, Python! ' 去除左侧空白
s.rstrip() # ' Hello, Python!' 去除右侧空白
'...test..'.strip('.') # 'test' 去除两端的点
5. 拆分与连接
# 拆分
'apple,banana,orange'.split(',') # ['apple', 'banana', 'orange']
'one two three'.split() # ['one', 'two', 'three'] 默认按空白分割
'one,two,three'.split(',', maxsplit=1)# ['one', 'two,three'] 限制拆分次数
'apple\nbanana'.splitlines() # ['apple', 'banana'] 按行分割
# 从右侧拆分
'www.example.com'.rsplit('.', 1) # ['www.example', 'com']
# 连接(拼接列表/元组为字符串)
', '.join(['a', 'b', 'c']) # 'a, b, c'
''.join(['H', 'e', 'l', 'l', 'o']) # 'Hello'
6. 对齐与填充
'42'.zfill(5) # '00042' 左侧用0填充至指定长度 'Hi'.ljust(10) # 'Hi ' 左对齐,默认填充空格 'Hi'.rjust(10) # ' Hi' 右对齐 'Hi'.center(10) # ' Hi ' 居中对齐 'Hi'.center(10, '-') # '----Hi----' 指定填充字符
7. 格式化
-
f-string(首选):
name = "Alice" age = 30 f"{name} is {age} years old." # 'Alice is 30 years old.' f"pi ≈ {3.14159:.2f}" # 'pi ≈ 3.14' -
format 方法:python
"{} is {} years old.".format(name, age) "{1} and {0}".format("A", "B") # 'B and A' "{name} is {age}".format(name="Bob", age=25)
8. 编码与转换
'你好'.encode('utf-8') # b'\xe4\xbd\xa0\xe5\xa5\xbd' 字符串 → 字节
b'\xe4\xbd\xa0'.decode('utf-8') # '你' 字节 → 字符串
# 字符与码点
ord('A') # 65
chr(65) # 'A'
9. 特殊函数
len(s) # 19 字符长度(含空格)
min('hello') # 'e'
max('hello') # 'o'
sorted('hello') # ['e', 'h', 'l', 'l', 'o'] 返回排序后的字符列表
reversed('hello') # 返回反向迭代器更多推荐
所有评论(0)