2026-02-05 21:12:32
Python字符串常见操作经典实例详解如下:
1. 字符串切片strip():去除首尾空格。
lstrip():去除左侧空格。
rstrip():去除右侧空格。
str = ' python str 'print(str.strip()) # 输出: python strsplit():默认按空格分隔,返回列表。
split(sep):按指定分隔符sep分割。
splitlines():按行分隔(支持n、r等)。
str = '1,2,3'print(str.split(',')) # 输出: ['1', '2', '3']join(seq):用指定字符连接序列元素。
str = '-'seq = ('a', 'b', 'c')print(str.join(seq)) # 输出: a-b-ccount(sub[, beg, end]):统计子字符串出现次数。
str = "thing example....wow!!!"print(str.count('i', 0, 5)) # 输出: 1find(sub):返回子字符串首次出现的索引,未找到返回-1。
index(sub):同find,但未找到时抛出ValueError。
rfind()/rindex():从右侧开始查找。
str1 = "this is string example....wow!!!"print(str1.find("exam")) # 输出: 15partition(sep):返回三元组(左, sep, 右)。
rpartition(sep):从右侧分割。
str = "replace(old, new[, max]):替换字符串,max限制替换次数。
str = "thing example....wow!!!"print(str.replace("is", "was", 2)) # 输出: thwas was example....wow!!!isdigit():是否全为数字(如"123")。
isnumeric()/isdecimal():针对Unicode数字。
isalpha():是否全为字母。
isalnum():是否为字母或数字。
isspace():是否全为空格。
islower()/isupper():大小写检测。
str = "123"print(str.isdigit()) # 输出: Truecapitalize():首字母大写,其余小写。
lower()/upper():全小写/大写。
swapcase():大小写互换。
max(str)/min(str):返回ASCII值最大/最小的字符。
len(str):字符串长度。
str = "Python"print(str.lower()) # 输出: pythoncenter(width[, fillchar]):居中并填充字符至指定宽度。
str = "wow"print(str.center(10, '*')) # 输出: *wowzfill(width):右对齐,左侧填充0。
str = "42"print(str.zfill(5)) # 输出: 00042%格式化:%s(字符串)、%d(整数)等。
print("Name: %s, Age: %d" % ("Alice", 25)) # 输出: Name: Alice, Age: 25按位置或关键字参数格式化。
print("{1}, {0}".format("b", "a")) # 输出: a, b总结:Python字符串操作涵盖切片、查找、替换、格式化等,灵活运用这些方法可高效处理文本数据。