python 字符串常用处理函数
以下是Python中字符串常用处理函数的系统整理,涵盖字符串创建、修改、查找、分割、判断等核心操作。根据功能分类说明,并附带简洁示例,方便快速查阅和使用。
📐 一、字符串创建与基础操作
创建字符串
Python支持单引号、双引号、三引号创建字符串:s1 = 'Hello' # 单引号 s2 = "World" # 双引号 s3 = '''Multi-line string''' # 三引号支持多行字符串[6](@ref)
访问字符与切片
- 索引:
str[index]
(索引从0开始,负数表示倒数)s = "Python" print(s[0]) # 'P'(首个字符) print(s[-1]) # 'n'(末尾字符)[6](@ref)
- 切片:
str[start:end:step]
s = "Python" print(s[1:4]) # 'yth'(索引1到3) print(s[::2]) # 'Pto'(步长为2)[1,6](@ref)
- 索引:
🔧 二、字符串修改与转换
方法 | 功能 | 示例 | 输出 |
---|---|---|---|
upper() | 转大写字母 | "Hello".upper() | "HELLO" |
lower() | 转小写字母 | "WORLD".lower() | "world" |
capitalize() | 首字母大写 | "hello".capitalize() | "Hello" |
title() | 每个单词首字母大写 | "hello world".title() | "Hello World" |
swapcase() | 大小写互换 | "HeLLo".swapcase() | "hEllO" |
replace(old, new[, count]) | 替换子串(count 指定次数) | "apple".replace("p", "b", 1) | "able" |
🔍 三、字符串查找与统计
方法 | 功能 | 示例 | 返回值 |
---|---|---|---|
find(sub[, start, end]) | 查找子串位置(未找到返回-1) | "hello".find("e") | 1 |
index(sub[, start, end]) | 同find() ,未找到抛出异常 | "hello".index("l") | 2 |
count(sub[, start, end]) | 统计子串出现次数 | "hello".count("l") | 2 |
startswith(prefix) | 检查是否以指定前缀开头 | "hello".startswith("he") | True |
endswith(suffix) | 检查是否以指定后缀结尾 | "world".endswith("ld") | True |
✂️ 四、字符串分割与拼接
分割
split(sep=None, maxsplit=-1)
:按分隔符切分(默认按空格)s = "a,b,c" print(s.split(",")) # ['a', 'b', 'c'][3,5](@ref)
splitlines([keepends])
:按行分割(keepends
保留换行符)s = "line1\nline2" print(s.splitlines()) # ['line1', 'line2'][4](@ref)
拼接
join(iterable)
:用字符串连接可迭代对象words = ["Hello", "World"] print("-".join(words)) # "Hello-World"[3](@ref)
🧹 五、空白与字符处理
方法 | 功能 | 示例 | 输出 |
---|---|---|---|
strip([chars]) | 移除两侧空白或指定字符 | " hi ".strip() | "hi" |
lstrip([chars]) | 移除左侧空白或指定字符 | " hi ".lstrip() | "hi " |
rstrip([chars]) | 移除右侧空白或指定字符 | " hi ".rstrip() | " hi" |
zfill(width) | 左侧用0填充至指定宽度 | "42".zfill(5) | "00042" |
🧪 六、字符串判断与检测
方法 | 功能 | 示例 | 返回值 |
---|---|---|---|
isalpha() | 是否全为字母 | "abc".isalpha() | True |
isdigit() | 是否全为数字 | "123".isdigit() | True |
isalnum() | 是否全为字母或数字 | "a1b2".isalnum() | True |
isspace() | 是否全为空白字符 | " ".isspace() | True |
islower() | 是否全为小写 | "hello".islower() | True |
🧩 七、格式化与对齐
方法 | 功能 | 示例 | 输出 |
---|---|---|---|
format(*args, **kwargs) | 格式化字符串(支持占位符{} ) | "{} {}".format("Hello", "World") | "Hello World" |
center(width[, fillchar]) | 居中并填充指定字符 | "hi".center(10, "-") | "----hi----" |
ljust(width[, fillchar]) | 左对齐并填充指定字符 | "hi".ljust(10, "*") | "hi********" |
rjust(width[, fillchar]) | 右对齐并填充指定字符 | "hi".rjust(10, "*") | "********hi" |
💎 八、其他实用函数
- 编码转换:
encode(encoding="utf-8")
:字符串→字节串decode()
:字节串→字符串s = "你好" b = s.encode("utf-8") # b'\xe4\xbd\xa0\xe5\xa5\xbd' b.decode("utf-8") # "你好"[5](@ref)
- 字符映射:
maketrans()
+translate()
:批量替换字符table = str.maketrans("ab", "12") print("abc".translate(table)) # "12c"[7](@ref)
💡 九、综合运用示例
s = " Hello World! "
# 去空白→转小写→替换→分割
processed = s.strip().lower().replace("world", "Python").split()
print(processed) # ['hello', 'Python!']
⚠️ 注意:字符串是不可变类型,所有修改操作均返回新字符串,原始字符串不变
。更多高级用法(如正则表达式)可参考re
模块。