因为字符串是不可变类型 —— 任何看似 “修改” 字符串的操作,本质上都必须创建新对象。
一、“转换型” 方法:明确返回新字符串(副本)
replace(old, new)
upper()
lower()
strip()
lstrip()
rstrip()
join(iterable)
replace()
split()
capitalize()
title()
s = "hello" print(s.upper()) # 输出 "HELLO"(新字符串) print(s) # 输出 "hello"(原字符串不变)print(s is s.upper()) False
二、“查询型” 方法:返回非字符串结果(不涉及副本)
startswith(prefix)
endswith(suffix)
find(sub)
index(sub)
str.find(sub)
s = "hello world, hello python" # 查找子串首次出现的位置 print(s.find("hello")) # 输出:0(第一个"hello"从索引0开始) print(s.find("o")) # 输出:4(第一个"o"在索引4) # 查找不存在的子串 print(s.find("java")) # 输出:-1(未找到) # 指定起始查找位置(从索引6开始找) print(s.find("hello", 6)) # 输出:13(第二个"hello"从索引13开始) # 指定起止查找范围(在索引5到15之间查找) print(s.find("o", 5, 15)) # 输出:7(范围内的第一个"o")
count(sub)
isalpha()
isdigit()
split(sep)
所有字符串方法都不会修改原字符串