张芷铭的个人博客

Python 字符串 API 提供丰富的处理方法,包括大小写转换、查找替换、拆分连接等。

大小写转换

1
2
3
4
s.lower()      # 小写
s.upper()      # 大写
s.capitalize() # 首字母大写
s.title()      # 每词首字母大写

去除空白

1
2
3
s.strip()   # 两端
s.lstrip()  # 左侧
s.rstrip()  # 右侧

查找与替换

方法返回值
s.find(sub)首次索引,未找到返回 -1
s.rfind(sub)末次索引
s.index(sub)首次索引,未找到抛异常
s.replace(old, new)替换后的新字符串
s.count(sub)出现次数

判断方法

1
2
3
4
5
6
s.isdigit()      # 仅数字
s.isalpha()      # 仅字母
s.isalnum()      # 字母或数字
s.isspace()      # 仅空白
s.startswith(p)  # 以 p 开头
s.endswith(s)    # 以 s 结尾

拆分与连接

1
2
3
4
s.split()        # 按空白拆分
s.split(sep)     # 按分隔符拆分
s.splitlines()   # 按行拆分
sep.join(list)   # 连接

对齐

1
2
3
4
s.center(width)  # 居中
s.ljust(width)   # 左对齐
s.rjust(width)   # 右对齐
s.zfill(width)   # 左侧补零

其他

1
2
s.partition(sep)   # 返回 (head, sep, tail)
len(s)             # 长度

Comments