字符串常用方法速查
字符串是 Python 里最常用的数据类型之一。这一页不追求把所有方法列完,只保留我平时最常回看的那一批。
大小写转换
text = "Hello World"
print(text.lower())
print(text.upper())
print(text.title())
去空白
text = " hello "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
查找与判断
text = "hello world"
print(text.find("world")) # 找不到时返回 -1
print(text.startswith("hello"))
print(text.endswith("world"))
print("world" in text)
替换
text = "2024-04-01"
print(text.replace("-", "/"))
分割与连接
text = "alice,bob,charlie"
parts = text.split(",")
print(parts)
print("-".join(parts))
字符类型判断
print("123".isdigit())
print("abc".isalpha())
print("abc123".isalnum())
print(" ".isspace())
格式化相关
name = "alice"
score = 95
print(f"{name}: {score}")
print("{:>8}".format(name))
print("3.14159 -> {:.2f}".format(3.14159))
一些我容易忘的点
find()找不到返回-1,不会报错。split()默认按任意空白切分。join()是分隔符字符串的方法,不是列表的方法。- 字符串是不可变对象,方法返回的是新字符串,不会原地修改。