python入门到脱坑 字符串——运算符
在Python中,字符串支持多种运算符操作,使得字符串处理更加灵活高效。以下是字符串运算符的全面详解:
一、字符串基本运算符
1. 拼接运算符+
s1 = "Hello"
s2 = "Python"
result = s1 + " " + s2 # "Hello Python"
2. 重复运算符*
s = "Hi"
print(s * 3) # "HiHiHi"
3. 成员运算符in/not in
text = "Python编程"
print("Py" in text) # True
print("Java" not in text) # True
二、比较运算符
字符串按字典序(ASCII/Unicode值)逐个字符比较:
print("apple" < "banana") # True(比较首字母ASCII码)
print("A" < "a") # True(A:65 < a:97)
print("中" > "美") # 比较Unicode编码(中:20013 > 美:32654)
常见比较场景:
运算符 | 说明 | 示例 |
== | 内容完全相同 | "hi" == "hi" → True |
!= | 内容不同 | "A" != "a" → True |
> | 字典序大于 | "b" > "a" → True |
< | 字典序小于 | "A" < "B" → True |
三、索引与切片运算符[]
1. 索引访问
s = "Python"
print(s[0]) # 'P'(正向索引,从0开始)
print(s[-1]) # 'n'(负向索引,-1表示最后一个)
2. 切片操作[start:end:step]
print(s[1:4]) # 'yth'(1到3号字符)
print(s[:3]) # 'Pyt'(从头开始到2号字符)
print(s[::2]) # 'Pto'(步长2)
print(s[::-1]) # 'nohtyP'(反转字符串)
四、格式化运算符%(旧式)
name = "Alice"
age = 25
print("%s is %d years old" % (name, age)) # "Alice is 25 years old"
占位符 | 类型 | 示例 |
%s | 字符串 | "%s" % "hi" |
%d | 整数 | "%03d" % 5 → "005" |
%f | 浮点数 | "%.2f" % 3.1415 → "3.14" |
五、字符串方法 vs 运算符
1. 拼接对比
# + 运算符
s = "a" + "b"
# join()方法(更高效处理多字符串)
parts = ["a", "b", "c"]
s = "".join(parts) # "abc"
2. 包含判断对比
# in 运算符
if "Py" in "Python": ...
# find()方法(可获取位置)
pos = "Python".find("Py") # 返回0(索引位置)
六、运算符优先级
字符串运算符优先级(从高到低):
- [](索引/切片)
- * +(重复/拼接)
- in not in == != 等比较运算符
示例:
print("a" + "b" * 2) # "abb"(先执行乘法)
print(("a" + "b") * 2) # "abab"(括号优先)
七、实用技巧
1. 快速构建分隔线
line = "-" * 30 # "------------------------------"
2. 密码掩码显示
password = "secret"
masked = password[:1] + "*" * (len(password)-1) # "s*****"
3. 多条件判断
if "admin" in username or "root" in username:
print("管理员账户")
八、注意事项
- 不可变性:所有运算符操作都返回新字符串
s = "hello"
s[0] = "H" # 报错!字符串不可直接修改
性能考虑:
- 避免循环中使用 + 拼接字符串(推荐 join())
- 频繁切片操作不影响性能(字符串不可变,切片共享内存)
编码问题:
print("á" == "a") # False(看似相同,但Unicode组合方式不同)
掌握这些运算符后,你可以更高效地处理字符串操作