在 Python 中,字符串(str)是 不可变(immutable)对象,但提供了大量 内置字符串方法(String Methods)来进行处理,如大小写转换、查找、替换、拆分等。下面按照 常见类别系统整理 Python 字符串方法。
一、大小写转换方法
1 lower()
将字符串转换为小写。
s = "Hello World"
print(s.lower())
输出:
hello world
2 upper()
转换为大写。
s = "hello"
print(s.upper())
输出:
HELLO
3 title()
每个单词首字母大写。
s = "hello world"
print(s.title())
输出:
Hello World
4 capitalize()
字符串首字母大写。
s = "hello world"
print(s.capitalize())
输出:
Hello world
5 swapcase()
大小写互换。
s = "Hello World"
print(s.swapcase())
输出:
hELLO wORLD
二、查找字符串
1 find()
查找子字符串,返回索引。
s = "hello world"
print(s.find("world"))
输出:
6
如果不存在:
-1
2 index()
类似 find(),但找不到会报错。
s.index("world")
错误:
ValueError
3 count()
统计出现次数。
s = "banana"
print(s.count("a"))
输出:
3
4 startswith()
s = "hello world"
print(s.startswith("hello"))
输出:
True
5 endswith()
print(s.endswith("world"))
三、字符串替换
replace()
s = "hello world"
print(s.replace("world", "python"))
输出:
hello python
限制替换次数:
s.replace("a","x",2)
四、字符串分割
1 split()
s = "a,b,c"
print(s.split(","))
输出:
['a', 'b', 'c']
2 rsplit()
从右侧开始分割。
s = "a,b,c"
print(s.rsplit(",",1))
输出:
['a,b', 'c']
3 splitlines()
s = "a\nb\nc"
print(s.splitlines())
输出:
['a', 'b', 'c']
五、字符串连接
join()
words = ["Python","is","great"]
print(" ".join(words))
输出:
Python is great
原理:
separator.join(iterable)
六、去除字符
1 strip()
去除两端空格。
s = " hello "
print(s.strip())
输出:
hello
2 lstrip()
左侧去除。
s.lstrip()
3 rstrip()
右侧去除。
s.rstrip()
指定字符
s = "***hello***"
print(s.strip("*"))
输出:
hello
七、字符串判断方法
1 isalpha()
是否全部为字母。
"hello".isalpha()
True
2 isdigit()
"123".isdigit()
True
3 isalnum()
字母或数字。
"abc123".isalnum()
4 isspace()
" ".isspace()
5 islower() / isupper()
"hello".islower()
"HELLO".isupper()
八、字符串对齐与填充
1 center()
"hello".center(20)
输出:
' hello '
2 ljust()
"hello".ljust(10)
3 rjust()
"hello".rjust(10)
4 zfill()
填充 0:
"42".zfill(5)
输出:
00042
九、字符串格式化
1 format()
"Hello {}".format("Alice")
输出:
Hello Alice
2 f-string(推荐)
name = "Alice"
print(f"Hello {name}")
十、编码与解码
encode()
s = "hello"
print(s.encode("utf-8"))
输出:
b'hello'
十一、字符串方法完整列表(常用)
| 方法 | 作用 |
|---|---|
| lower | 小写 |
| upper | 大写 |
| title | 标题格式 |
| capitalize | 首字母大写 |
| swapcase | 大小写交换 |
| find | 查找 |
| index | 查找 |
| count | 统计 |
| replace | 替换 |
| split | 分割 |
| join | 连接 |
| strip | 去空格 |
| startswith | 开头判断 |
| endswith | 结尾判断 |
| isalpha | 字母判断 |
| isdigit | 数字判断 |
十二、字符串不可变特性
在 Python 中:
s = "hello"
s.upper()
不会修改原字符串:
print(s)
仍然是:
hello
必须:
s = s.upper()
✅ 总结
Python 字符串方法主要分为:
- 大小写转换
- 查找统计
- 替换
- 分割连接
- 去除字符
- 字符串判断
- 格式化与填充
这些方法构成了 Python 文本处理的核心工具。
如果你愿意,我可以再给你整理一个 Python字符串方法速查表(50+方法完整分类),很多高级开发者也会收藏这一份。