讲解
字符串对象自带几十个方法,全部遵守「返回新串、不改原串」的约定。最高频的一组是查找与判断:'abc'.startswith('ab') 判断开头、endswith 判断结尾、in 运算符判断包含、find 找子串位置(找不到返回 -1)、index 也找位置(找不到抛异常)、count 统计出现次数。日常包含判断优先用简洁的 in:if 'error' in log_line。
第二组是变换:upper/lower 转大小写、strip 去掉两端空白(lstrip/rstrip 只去一边)、replace 替换、title 首字母大写、swapcase 大小写互换。strip 在处理用户输入和文件内容时几乎必用——用户敲的空格、文件行尾的换行符都靠它清理。replace(old, new) 替换所有出现的子串,可选第三个参数限制次数。
第三组是拆分与组合:split 按分隔符把字符串拆成列表(不传参数时按任意空白拆,并自动忽略连续空白)、rsplit 从右边拆、splitlines 按行拆、partition 拆成「前、分隔符、后」三元组;反向操作就是上一节学的 join。还有一组判断字符类别的方法:isdigit 是否全是数字、isalpha 是否全是字母、isalnum、isspace,做简单输入校验很方便。这些方法可以链式调用:text.strip().lower().replace(' ', '-') 一气呵成。
示例
text = ' Python 很有趣 '
print('原始长度:', len(text))
clean = text.strip()
print('去空格后:', f'[{clean}]')
# 查找与判断
url = 'https://docs.ohmygp.com/python/strings'
print('以 https 开头:', url.startswith('https'))
print('包含 docs:', 'docs' in url)
print('python 的位置:', url.find('python'))
print('斜杠出现次数:', url.count('/'))
# 大小写与替换
print('大写:', 'hello'.upper(), ',小写:', 'HELLO'.lower())
print('替换:', 'aaa'.replace('a', 'b', 2)) # 只换前 2 个
# 拆分与组合
line = '小明,18,北京'
fields = line.split(',')
print('拆成列表:', fields)
print('组合回去:', ' | '.join(fields))
# split 无参:按任意空白拆,连续空白算一个
print('按空白拆:', 'a b c\td'.split())
# 字符类别判断
for token in ['123', 'abc', 'abc123', '3.14']:
print(f'{token!r:>10} isdigit={token.isdigit()} isalpha={token.isalpha()}')
# 链式调用
raw = ' Hello World '
print('链式:', raw.strip().lower().replace(' ', '-'))
常见坑
- 期待方法修改原串:s.upper() 之后 s 纹丝不动,必须接收返回值:s = s.upper()。这是字符串不可变性决定的。
- find 和 index 不分:find 找不到返回 -1(而 -1 恰好是合法的「倒数第一」下标,容易误判),index 找不到抛 ValueError。要明确处理「找不到」的分支。
- isdigit 判断不了小数和负数:'3.14'.isdigit() 和 '-5'.isdigit() 都是 False。校验数字输入更稳的做法是 try 一下 float()。
- split 无参与 split(' ') 不同:无参时连续空白算一个分隔且忽略首尾空白;split(' ') 会把连续空格拆出空字符串。
小结
查找判断用 in/find/count,变换用 strip/lower/replace,拆分组合用 split/join,全部返回新串可链式调用。下一节看布尔值与特殊的 None。