在Python中,字符串是不可变序列类型,提供了丰富的内置方法。以下是常用的字符串操作方法及示例:
1. 大小写转换
-
lower() 转小写
-
upper() 转大写
-
capitalize() 首字母大写
-
title() 每个单词首字母大写
-
swapcase() 大小写互换
print("HELLO".lower()) # hello
print("hello".upper()) # HELLO
print("python".capitalize()) # Python
print("hello world".title()) # Hello World
print("PyThon".swapcase()) # pYtHON
2. 查找与替换
-
find(sub, start, end):查找子串,返回索引,找不到返回-1,start 和 end 为可选参数
-
rfind(sub):从右侧查找子串
-
index(sub):类似find(),但找不到时会报错
- replace(old, new, count):替换子串,count指定替换次数为可选参数
print("apple".find("p")) #1
print("apple".find("p",3)) # -1print("apple".rfind("p")) # 2
print("apple".index("p")) # 1 找不到报错
print("banana".replace("a", "o", 2)) # bonona
3. 字符串判断
-
startswith(prefix, start, end):是否以指定前缀开头,start 和 end 为可选参数
-
endswith(suffix):是否以指定后缀结尾
-
isalpha():是否全为字母
-
isdigit():是否全为数字
-
isalnum():是否全为字母或数字
-
isspace():是否全为空白符
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
print("123ABC".isdigit()) # False
print("123".isdigit()) # True
print("123ABC".isalnum()) # True
print("\t \n".isspace()) # True
4. 分割与连接
-
split(sep,maxsplit) :按分隔符分割为列表
-
rsplit(sep,maxsplit): 从右侧分割字符
-
splitlines():按行分割
-
join(iterable):连接字符串序列
print("a,b,c".split(",",1)) #['a', 'b,c']
print("a,b,c".rsplit(",",1)) #['a,b', 'c']
print("line1\nline2".splitlines()) # ['line1', 'line2']
print("!".join(["a", "b", "c"]) ) #a!b!c
5. 空白处理
-
strip():移除两侧空白或指定字符
-
lstrip():移除左侧空白或指定字符
-
rstrip():移除右侧空白或指定字符
print(" hello ".strip()) # hello
print("xxxworld".lstrip("xxx")) # world
print("helloxxx".rstrip("xxx")) # hello
6. 对齐与填充
-
center(width):居中填充
-
ljust(width):左对齐填充
-
rjust(width):右对齐填充
-
zfill(width):左侧用0填充
print("center".center(8,'0')) # 0center0
print("hello".ljust(8,'0')) # hello000
print("hello".rjust(8,'0')) #000hello
print("hello".zfill(10)) #00000hello
7. 格式化
-
f 格式化字符串
-
format() 格式化表达式
name = "Alice"
print(f"Hello, {name}!") #Hello, Alice!
print("{0} + {1} = {2}".format(1, 2, 3)) #1 + 2 = 3
8. 其他操作
-
len(str):获取字符串长度
-
in:检查字符串存在某个字符
-
not in:检查字符串不存在某个字符
-
count(sub,start,end):统计子串出现次数
-
encode(encoding="utf-8"):编码为字节
print(len("hello world")) # 11
print("a" in("apple")) # True
print("o" not in("apple")) #True
print("aaabbbccc".count("a",0,2)) #2
print("你好".encode(encoding="utf-8")) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
掌握这些方法可高效处理文本数据,注意字符串不可变性:所有操作均返回新字符串,原字符串不变。