# 敏感词过滤
text ="这个产品太垃圾了!"
bad_words =["垃圾","废物","差劲"]for word in bad_words:text = text.replace(word,"**")print(text)# 输出: "这个产品太**了!"
三、字符串判断方法
1. 内容判断方法
方法
作用
示例
结果
startswith(prefix)
是否以某子串开头
"hello".startswith("he")
True
endswith(suffix)
是否以某子串结尾
"world".endswith("ld")
True
isalnum()
是否字母或数字
"abc123".isalnum()
True
isalpha()
是否全为字母
"abc".isalpha()
True
isdigit()
是否全为数字
"123".isdigit()
True
isnumeric()
是否数字字符
"Ⅷ".isnumeric()
True
isdecimal()
是否十进制数字
"12".isdecimal()
True
isspace()
是否全为空白字符
" ".isspace()
True
islower()
是否全小写
"hello".islower()
True
isupper()
是否全大写
"HELLO".isupper()
True
istitle()
是否标题化(首字母大写)
"Hello".istitle()
True
# 密码强度验证
password ="Passw0rd!"
has_upper =any(c.isupper()for c in password)
has_lower =any(c.islower()for c in password)
has_digit =any(c.isdigit()for c in password)
has_special =any(not c.isalnum()for c in password)print(f"密码强度: {has_upper and has_lower and has_digit and has_special}")
四、字符串分割与连接方法(常用)
1. 分割方法
方法
作用
示例
结果
split(sep)
按分隔符分割
"a,b,c".split(",")
['a', 'b', 'c']
rsplit(sep)
从右开始分割
"a,b,c".rsplit(",", 1)
['a,b', 'c']
splitlines()
按行分割
"第一行\n第二行".splitlines()
['第一行', '第二行']
partition(sep)
分成三部分
"hello.world".partition(".")
('hello', '.', 'world')
rpartition(sep)
从右分成三部分
"hello.world.py".rpartition(".")
('hello.world', '.', 'py')
# 解析URL参数
url ="https://example.com?name=John&age=25"
_, params = url.split("?",1)# 分割一次
params_dict =dict(p.split("=")for p in params.split("&"))print(params_dict)# 输出: {'name': 'John', 'age': '25'}
2. 连接方法
方法
作用
示例
结果
join(iterable)
连接字符串序列
",".join(["a","b","c"])
"a,b,c"
# 路径拼接
parts =["C:","Users","John","Documents"]
path ="\\".join(parts)# Windows路径print(path)# 输出: C:\Users\John\Documents