Python字符串方法包括大小写转换、查找替换、去空白、判断检查及分割连接,如upper()、find()、strip()、startswith()、split()等,均返回新字符串,原串不变。
Python 中字符串是不可变的序列类型,提供了丰富的内置方法来操作和处理文本。以下是一些最常用且实用的字符串方法,适合日常开发使用。
1. 大小写转换
用于调整字符串的字母大小写格式。
str.upper()
:返回所有字符转为大写的副本
str.lower()
:返回所有字符转为小写的副本
str.capitalize()
:首字母大写,其余小写
str.title()
:每个单词首字母大写
str.swapcase()
:大小写互换
示例:
2. 查找与替换
用于在字符串中查找子串或进行内容替换。
str.find(sub)
:返回子串首次出现的索引,未找到返回 -1
str.index(sub)
:类似 find,但找不到会抛出 ValueError
str.count(sub)
:统计子串出现次数
str.replace(old, new)
:返回将 old 替换为 new 的新字符串
示例:
3. 去除空白与填充
常用于清理用户输入或
格式化输出
。
立即学习
“
Python免费学习笔记(深入)
”;
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
str.strip()
:去除首尾空白字符(空格、换行、制表符)
str.lstrip()
:仅去左边空白
str.rstrip()
:仅去右边空白
str.center(width)
:居中并填充空格到指定宽度
str.zfill(width)
:左补 0 到指定长度
示例:
4. 判断与检查
用于验证字符串的内容特征,返回布尔值。
str.startswith(prefix)
:是否以指定前缀开头
str.endswith(suffix)
:是否以指定后缀结尾
str.isdigit()
:是否全为数字
str.isalpha()
:是否全为字母
str.isalnum()
:是否由字母和数字组成
str.isspace()
:是否全为空白字符
str.islower()
:是否全小写
str.isupper()
:是否全大写
示例:
5. 分割与连接
处理文本解析和组合时非常关键。
str.split(sep)
:按分隔符分割成列表,默认按空白分割
str.splitlines()
:按行分割,忽略换行符
str.join(iterable)
:用字符串连接
可迭代对象
中的元素
示例:
基本上就这些。掌握这些方法能应对大多数字符串处理场景。实际使用时注意它们都返回新字符串,原字符串不变。
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.title()) # Hello World
s = "apple apple banana"
print(s.find("apple")) # 0
print(s.count("apple")) # 2
print(s.replace("a", "A")) # Apple Apple bAnAnA
name = " john "
print(name.strip()) # john
num = "42"
print(num.zfill(5)) # 00042
s = "Hello123"
print(s.isalpha()) # False
print(s.isalnum()) # True
print(s.startswith("He")) # True
line = "apple,banana,cherry"
fruits = line.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
words = ["I", "love", "Python"]
sentence = " ".join(words)
print(sentence) # I love Python
