Python “字符串” 经典范例 :20 个使用方法与技巧
以下是 Python 中字符串的 20 个经典使用实例,涵盖了常见的字符串操作和应用场景:
1. 字符串反转
将字符串反转是经典的面试题之一,可以使用切片轻松实现。
s = "hello"
reversed_s = s[::-1]
print(reversed_s) # 输出 "olleh"
2. 检查回文字符串
回文字符串是指正读和反读都相同的字符串(如 “madam”)。
def is_palindrome(s):return s == s[::-1]print(is_palindrome("madam")) # 输出 True
print(is_palindrome("hello")) # 输出 False
3. 统计字符出现次数
统计字符串中某个字符或子字符串的出现次数。
s = "hello world"
count = s.count("l")
print(count) # 输出 3
4. 字符串分割与连接
将字符串按特定分隔符分割,或将列表中的字符串连接成一个字符串。
# 分割
s = "apple,banana,orange"
fruits = s.split(",")
print(fruits) # 输出 ['apple', 'banana', 'orange']# 连接
new_s = "-".join(fruits)
print(new_s) # 输出 "apple-banana-orange"
5. 字符串格式化
使用 f-string
或 format()
方法动态生成字符串。
name = "Alice"
age = 25
# 使用 f-string
print(f"My name is {name} and I am {age} years old.")
# 使用 format()
print("My name is {} and I am {} years old.".format(name, age))
6. 去除字符串空白
去除字符串开头和结尾的空白字符(如空格、换行符等)。
s = " hello world "
trimmed_s = s.strip()
print(trimmed_s) # 输出 "hello world"
7. 查找子字符串
查找子字符串在字符串中的位置。
s = "hello world"
index = s.find("world")
print(index) # 输出 6
8. 替换字符串中的内容
将字符串中的某个子字符串替换为另一个字符串。
s = "hello world"
new_s = s.replace("world", "Python")
print(new_s) # 输出 "hello Python"
9. 检查字符串的开头或结尾
检查字符串是否以某个前缀开头或以某个后缀结尾。
s = "hello world"
print(s.startswith("hello")) # 输出 True
print(s.endswith("world")) # 输出 True
10. 字符串加密与解密
实现简单的字符串加密(如 Caesar Cipher,凯撒密码)。
def caesar_cipher(text, shift):result = ""for char in text:if char.isalpha():shift_amount = shift % 26if char.islower():result += chr(((ord(char) - ord('a') + shift_amount) % 26) + ord('a'))else:result += chr(((ord(char) - ord('A') + shift_amount) % 26) + ord('A'))else:result += charreturn result# 加密
encrypted = caesar_cipher("hello", 3)
print(encrypted) # 输出 "khoor"# 解密
decrypted = caesar_cipher(encrypted, -3)
print(decrypted) # 输出 "hello"
11. 字符串对齐处理
使用 ljust()、rjust() 和 center() 方法对字符串进行对齐。
s = "hello"
print(s.ljust(10, "-")) # 输出 "hello-----"
print(s.rjust(10, "-")) # 输出 "-----hello"
print(s.center(10, "-")) # 输出 "--hello---"
12. 检查字符串是否包含特定字符
使用 in 关键字检查字符串是否包含某个字符或子字符串。
s = "hello world"
print("world" in s) # 输出 True
print("python" in s) # 输出 False
13. 字符串的逐字符操作
遍历字符串中的每个字符并进行操作。
s = "hello"
for char in s:print(char.upper(), end=" ") # 输出 "H E L L O "
14. 字符串的重复
使用 * 运算符重复字符串。
s = "hello"
repeated_s = s * 3
print(repeated_s) # 输出 "hellohellohello"
15. 字符串的切片与步长
使用切片和步长提取字符串中的特定部分。
s = "hello world"
# 提取偶数索引的字符
print(s[::2]) # 输出 "hlowrd"# 反转字符串
print(s[::-1]) # 输出 "dlrow olleh"
16. 切片与字符串操作结合
切片可以与其他字符串操作结合使用。
s = "Python Programming"# 提取前 6 个字符并转换为大写
print(s[:6].upper()) # 输出 "PYTHON"# 提取最后 5 个字符并反转
print(s[-5:][::-1]) # 输出 "gnimm"
17. 字符串多层切片操作
可以对切片结果再次切片。
s = "Python Programming"# 先提取 "Programming",再提取前 5 个字符
print(s[7:][:5]) # 输出 "Progr"
18. 字符串与列表的转换
list(str):将字符串转换为字符列表。
“”.join(list):将字符列表合并为字符串。
s = "hello"
char_list = list(s) # 转换为列表 ['h', 'e', 'l', 'l', 'o']
new_s = "".join(char_list) # 合并为字符串 "hello"
19. 字符串查找与替换
s = "hello world"
print(s.find("world")) # 输出 6
print(s.replace("world", "Python")) # 输出 "hello Python"
print(s.count("l")) # 输出 3
- 1
- 2
- 3
- 4
20. 字符串编码与解码
s = "hello"
encoded = s.encode("utf-8") # 编码为字节
print(encoded) # 输出 b'hello'
decoded = encoded.decode("utf-8") # 解码为字符串
print(decoded) # 输出 "hello"
- 1
- 2
- 3
- 4
- 5
- 6
总结
这些实例涵盖了字符串的常见操作,包括反转、查找、替换、格式化、加密等。掌握这些经典用法,可以解决大多数字符串处理问题!