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