Python 字符串常用方法
说明: 本文内容由主要由DeepSeek生成,用于总览和备查。
- 不可变性:所有字符串方法都返回新字符串,不修改原字符串
- 链式调用:支持方法连续调用 str.strip().lower().replace("World", "Python")
| 分类 | 方法 | 描述 | 示例 |
|---|---|---|---|
| 大小写 | upper() | 转换为大写 | "hello".upper() → "HELLO" |
| lower() | 转换为小写 | "HELLO".lower() → "hello" | |
| capitalize() | 首字母大写 | "hello".capitalize() → "Hello" | |
| title() | 每个单词首字母大写 | "hello world".title() → "Hello World" | |
| swapcase() | 大小写互换 | "Hello".swapcase() → "hELLO" | |
| isupper() | 是否全部大写 | "HELLO".isupper() → True | |
| islower() | 是否全部小写 | "hello".islower() → True | |
| istitle() | 是否标题格式 | "Hello World".istitle() → True | |
| 查找操作 | find(sub) | 查找子串,返回索引 | "hello".find("e") → 1 |
| rfind(sub) | 从右侧查找 | "hello".rfind("l") → 3 | |
| index(sub) | 类似find,找不到报错 | "hello".index("e") → 1 | |
| rindex(sub) | 从右侧index | "hello".rindex("l") → 3 | |
| count(sub) | 统计出现次数 | "hello".count("l") → 2 | |
| 替换操作 | replace(old, new) | 替换子串 | "hi".replace("hi", "hello") → "hello" |
| translate(table) | 用于对字符串中的字符进行映射转换或删除操作。它通常与 str.maketrans() 方法配合使用 | table = str.maketrans('xyz', 'abc') result="xyz123".translate(table)print(result) 输出: abc123 | |
| 空白处理 | strip() | 去除两侧空白 | " hello ".strip() → "hello" |
| lstrip() | 去除左侧空白 | " hello ".lstrip() → "hello " | |
| rstrip() | 去除右侧空白 | " hello ".rstrip() → " hello" | |
| strip(chars) | 去除指定字符 | "xxhello".strip("x") → "hello" | |
| 填充对齐 | center(width) | 居中填充 | "hi".center(5) → " hi " |
| ljust(width) | 左对齐填充 | "hi".ljust(5) → "hi " | |
| rjust(width) | 右对齐填充 | "hi".rjust(5) → " hi" | |
| zfill(width) | 左侧补零 | "42".zfill(5) → "00042" | |
| 分割操作 | split(sep) | 按分隔符分割 | "a,b,c".split(",") → ["a","b","c"] |
| rsplit(sep) | 从右侧分割 | "a,b,c".rsplit(",",1) → ["a,b","c"] | |
| splitlines() | 按行分割 | "a\nb".splitlines() → ["a","b"] | |
| partition(sep) | 分成三部分 | "a@b".partition("@") → ("a","@","b") | |
| rpartition(sep) | 从右侧分区 | "a@b@c".rpartition("@") → ("a@b","@","c") | |
| 连接操作 | join(iterable) | 连接可迭代对象 | ",".join(["a","b"]) → "a,b" |
| 字符判断 | isalpha() | 是否全部字母 | "hello".isalpha() → True |
| isdigit() | 是否全部数字 | "123".isdigit() → True | |
| isalnum() | 是否字母或数字 | "abc123".isalnum() → True | |
| isdecimal() | 是否十进制数字 | "123".isdecimal() → True | |
| isnumeric() | 是否数字字符 | "½".isnumeric() → True | |
| isascii() | 是否ASCII字符 | "hello".isascii() → True | |
| isspace() | 是否空白字符 | " ".isspace() → True | |
| isprintable() | 是否可打印字符 | "hello".isprintable() → True | |
| 前后缀判断 | startswith(prefix) | 是否以指定开 | "hello".startswith("he") → True |
| endswith(suffix) | 是否以指定结尾 | "hello".endswith("lo") → True | |
| 格式化 | format(*args) | 格式化字符串 | "{}".format("hi") → "hi" |
| format_map(mapping) | 使用映射格式化 | "{k}".format_map({"k":"v"}) → "v" | |
| 编码转换 | encode(encoding) | 编码为字节 | "hi".encode() → b"hi" |

浙公网安备 33010602011771号