Python 字符串处理技巧:10个实用方法

Python 字符串处理为什么重要?

字符串是编程中最常见的数据类型之一,掌握字符串处理技巧能让你的代码更简洁高效。

1. 字符串格式化

name = '小明'
age = 18

# f-string(推荐)
print(f'我叫{name},今年{age}岁')

# format()
print('我叫{},今年{}岁'.format(name, age))

2. 字符串拼接

words = ['Python', 'is', 'awesome']
result = ' '.join(words)  # 'Python is awesome'

3. 字符串查找

text = 'Hello Python World'
print(text.find('Python'))   # 6
print(text.count('o'))       # 2

4. 字符串替换

text = 'I love Python'
new_text = text.replace('Python', '编程')
print(new_text)  # I love 编程

5. 大小写转换

text = 'Hello World'
print(text.upper())      # HELLO WORLD
print(text.lower())      # hello world

6. 去除空白

text = '  hello  '
print(text.strip())    # 'hello'

7. 判断字符串

print('abc'.isalpha())   # True
print('123'.isdigit())   # True

8. 拆分与组合

text = 'apple,banana,orange'
fruits = text.split(',')  # ['apple', 'banana', 'orange']

9. 检查前缀后缀

url = 'https://www.example.com'
print(url.startswith('https'))  # True
print(url.endswith('.com'))     # True

10. 字符串反转

text = 'Python'
reversed_str = text[::-1]  # 'nohtyP'

总结

这10个字符串处理技巧覆盖了日常开发中90%以上的场景。多练习多使用,自然就记住了。