Python 字符串方法备忘单
Python 字符串操作的完整参考指南。掌握格式化、搜索、拆分、替换和检查字符串属性。
常见的字符串格式化方法
用于改变字符串大小写、对齐方式和间距的方法。
| 方法/功能 | 语法 | 描述 |
|---|---|---|
| upper() | text.upper() | 将字符串中的所有字符转换为大写。 |
| lower() | text.lower() | 将字符串中的所有字符转换为小写。 |
| strip() | text.strip() | 删除前导和尾随空格。 |
| replace() | text.replace(old, new) | 将所有出现的子字符串替换为另一个子字符串。 |
字符串搜索和检查
查找索引、计算出现次数和检查字符串前缀/后缀的方法。
| 方法/功能 | 语法 | 描述 |
|---|---|---|
| find() | text.find(sub) | 如果找到则返回子字符串的最低索引,否则返回 -1。 |
| count() | text.count(sub) | 返回子字符串不重叠出现的次数。 |
| startswith() | text.startswith(prefix) | 如果字符串以指定前缀开头,则返回 True。 |
| endswith() | text.endswith(suffix) | 如果字符串以指定后缀结尾,则返回 True。 |
交互式演示脚本
run_all_cheat_methods.py
在编辑器中运行# upper()
text.upper()
# lower()
text.lower()
# strip()
text.strip()
# replace()
text.replace(old, new)
# find()
text.find(sub)
# count()
text.count(sub)
# startswith()
text.startswith(prefix)
# endswith()
text.endswith(suffix)常见问题解答
字符串方法会修改原始字符串吗?
不,Python 中的字符串是不可变的。字符串方法始终返回一个新字符串并保持原始字符串不变。
find() 和index() 有什么区别?
如果未找到子字符串,find() 返回 -1,而 index() 会引发 ValueError 异常。
相关主题
推荐的 Python 资源
通过相关的交互式教程、备忘单和代码比较来扩展您的知识。