Python字符串方法速查表大全

字符串的使用方法

Python 字符串是不可变序列,所有方法都返回新字符串,不修改原字符串。

在ipython3中定义一个字符串,例如hi_str="",输入hi_str.后按下Tab键,ipython会提示字符串能够使用的方法。按功能分类整理如下:

目录

1.判断类型

2.查找替换

3.大小写转换

4.填充与对其

5.去除空白符

6.分隔与合并

7.替换与修改

8.格式化输出

9.编码与解码

10.其他实用方法

1.判断类型

|--------------|--------------------------|--------------------------------|
| 方法 | 说明 | 示例 |
| .isdigit() | 是否只包含数字、数字序号⑴ 、unicode编码 | print("123".isdigit()) #→ True |
| .isspace() | 是否全是空白字符(含空格、换行、制表符等) | " \n".isspace() #→True |
| .isalnum() | 是否全是字母或数字 | "Hello123".isalnum() → True |
| .isalpha() | 是否全是字母和中文(不能有空格和符号) | "Hello你好".isalpha() → True |
| .isdecimal() | 是否只包含数字 | "123".isdecimal() → True |
| .isnumeric() | 是否只包含数字、含中文数字 | "壹仟0三".isnumeric()→ True |
| .istitle() | 是否标题化格式(所有单词的首字母大写) | "Hello World".istitle() → True |
| .islower() | 是否全是小写 | "hello".islower() → True |
| isupper() | 是否全是大写 | "HELLO".isupper() → True |

2.查找替换

|---------------------------------------|--------------------|-----------------------------------|
| 方法 | 说明 | 示例 |
| .startswith(prefix,start\[,end]) | 是否以指定前缀开头,范围可选 | "hello".startswith("he") → True |
| .endswith(prefix,start\[,end]) | 是否以指定后缀结尾,范围可选 | "hello".endswith("lo") → True |
| .find(sub, start\[, end]) | 查找str首次出现位置找不到返回-1 | "hello".find("l") → 2 |
| .rfind(sub, start\[, end]) | 从右向左查找,找不到返回-1 | "hello".rfind("l") → 3 |
| .index(sub, start\[, end]) | 查找str首次出现位置,找不到报错 | "hello".index("l") → 2 |
| .rindex(sub, start\[, end]) | 从右向左查找,找不到会报错 | "hello".rindex("l") → 3 |
| .replace(old, new, count) | 替换,替换次数count可选 | "hello".replace("l","x")→ "hexxo" |

3.大小写转换

|---------------|--------------------|-------------------------------------------|
| 方法 | 说明 | 示例 |
| .capitalize() | 字符串首字母大写 | "hello world".capitalize()→ "Hello world" |
| .title() | 每个单词首字母大写 | "hello world".title() →"Hello World" |
| .lower() | 所有大写转为小写 | "HELLO".lower() → "hello" |
| .upper() | 所有小写转为大写 | "hello".upper() → "HELLO" |
| .swapcase() | 大小写互换 | "Hello".swapcase() → "hELLO" |
| .casefold() | 更强大的小写转换(用于不区分大小写) | "ß".casefold() → "ss" |

4.填充与对其

|--------------------------|----------------|-----------------------------------|
| 方法 | 说明 | 示例 |
| .ljust(width, fillchar) | 左对齐,用指定字符串填充 | "hi".ljust(4, "*") → "hi**" |
| .rjust(width, fillchar) | 右对齐,用指定字符串填充 | "hi".rjust(4, "*") → "**hi" |
| .center(width, fillchar) | 居中对齐,用指定字符串填充 | "hi".center(5, "*") → "*hi**" |
| .zfill(width) | 指定长度,右对齐,左边0填充 | "68".zfill(5) → "00068" |
| .expandtabs(tabsize) | 将制表符替换为空格 | "a\tb".expandtabs(4) → "a b" |

5.去除空白符

|----------------|------------------|-----------------------------|
| 方法 | 说明 | 示例 |
| .lstrip(chars) | 去除左侧指定字符 | " hello".lstrip() → "hello" |
| .rstrip(chars) | 去除右侧指定字符 | "hello ".rstrip() → "hello" |
| .strip(chars) | 去除两端指定字符(默认去除空白) | " hello ".strip() → "hello" |

6.分隔与合并

|------------------------|---------------------|---------------------------------------------|
| 方法 | 说明 | 示例 |
| .split(sep, maxsplit) | 按分隔符分隔成列表(默认空白) | "a,b,c".split(",") → 'a','b','c' |
| .rsplit(sep, maxsplit) | 从右向左分隔 | "a,b,c".rsplit(",", 1) → 'a,b', 'c' |
| .splitlines(keepends) | 按行分隔成列表 | "a\nb".splitlines() → 'a','b' |
| .partition(sep) | 分成三部分:分隔符前、分隔符、分隔符后 | "a,b,c".partition(",") → ('a', ',', 'b,c') |
| .rpartition(sep) | 从右向左分隔成三部分 | "a,b,c".rpartition(",") → ('a,b', ',', 'c') |
| .join(iterable) | 用字符串连接可迭代对象(重要!) | ",".join('a','b') → "a,b" |

7.替换与修改

|-------------------------------|------------------|-----------------------------------|
| 方法 | 说明 | 示例 |
| translate(table) | 根据映射表替换字符 | 见下方示例 |
| maketrans(x, y, z) | 创建翻译映射表 | 配合 translate() 使用 |
| .replace(old, new, count) | 替换,替换次数count可选 | "hello".replace("l","x")→ "hexxo" |
| .lstrip(chars) | 去除左侧指定字符 | " hello".lstrip() → "hello" |
| .rstrip(chars) | 去除右侧指定字符 | "hello ".rstrip() → "hello" |
| .strip(chars) | 去除两端指定字符(默认去除空白) | " hello ".strip() → "hello" |
| .replace(old, new, count) | 替换,替换次数count可选 | "hello".replace("l","x")→ "hexxo" |

8.格式化输出

|-----------------------------|-----------------|---------------------------------------|
| 方法 | 说明 | 示例 |
| f-string | Python 3.6+ 格式化 | f"{name}" |
| % 操作符 | 旧式格式化 | "%s %s" % ("Hello", "World") |
| .format(*args, **kwargs) | 格式化字符串 | "{} {}".format("Hello", "World") |
| .format_map(mapping) | 用字典格式化 | "{name}".format_map({'name':'Alice'}) |

9.编码与解码

|--------------------------|----------|-----------------------------|
| 方法 | 说明 | 示例 |
| .encode(encoding,errors) | 字符串编码为字节 | "hello".encode() → b'hello' |
| .decode(encoding,errors) | 字节解码为字符串 | b'hello'.decode() → "hello" |

10.其他实用方法

|------------|---------------|-------------------------------------------|
| 方法 | 说明 | 示例 |
| len()函数 | 获取字符串长度(内置函数) | len("hello") → 5 |
| in 运算符 | 检查子串是否存在 | "h" in "hello" → True |
| sorted()函数 | 对字符串字符排序 | sorted("hello") → 'e','h','l','l','o' |

完整字符串方法速查表

python 复制代码
# 按字母排序的所有字符串方法
str.capitalize()       # 首字母大写
str.casefold()         # 小写转换(用于比较)
str.center()           # 居中对齐
str.count()            # 统计子串出现次数
str.encode()           # 编码为字节
str.endswith()         # 判断结尾
str.expandtabs()       # 扩展制表符
str.find()             # 查找子串(左到右)
str.format()           # 格式化
str.format_map()       # 用字典格式化
str.index()            # 查找子串(找不到报错)
str.isalnum()          # 是否字母或数字
str.isalpha()          # 是否全是字母
str.isascii()          # 是否全是 ASCII
str.isdecimal()        # 是否十进制数字
str.isdigit()          # 是否全是数字
str.isidentifier()     # 是否合法标识符
str.islower()          # 是否全小写
str.isnumeric()        # 是否全是数字(含中文)
str.isprintable()      # 是否可打印
str.isspace()          # 是否全是空白
str.istitle()          # 是否符合标题格式
str.isupper()          # 是否全大写
str.join()             # 连接序列
str.ljust()            # 左对齐
str.lower()            # 转小写
str.lstrip()           # 去除左侧字符
str.maketrans()        # 创建翻译表
str.partition()        # 分割成三部分(左)
str.removeprefix()     # 删除前缀 (Python 3.9+)
str.removesuffix()     # 删除后缀 (Python 3.9+)
str.replace()          # 替换子串
str.rfind()            # 查找子串(右到左)
str.rindex()           # 查找子串(右到左,报错)
str.rjust()            # 右对齐
str.rpartition()       # 分割成三部分(右)
str.rsplit()           # 从右分割
str.rstrip()           # 去除右侧字符
str.split()            # 分割成列表
str.splitlines()       # 按行分割
str.startswith()       # 判断开头
str.strip()            # 去除两端字符
str.swapcase()         # 大小写互换
str.title()            # 标题格式
str.translate()        # 翻译替换
str.upper()            # 转大写
str.zfill()            # 补零填充

字符串方法演示

1.判断空白字符

python 复制代码
# 1.判断空白字符
# space_str = "" # 输出:False
# space_str = " " #输出:True
space_str ="\n\t\r" #输出:True  \n\t\r属于空白字符
print(space_str.isspace())

2.判断字符串中是否只包含数字

python 复制代码
# 2.判断字符串中是否只包含数字
num_str = "8"
# num_str = "⑴"
# num_str = "\u00b2"
# num_str = "壹千零一"
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
# 三种方法都返回True 。
# 若将变量值改为unicode字符串"\u00b2"或数字序号⑴时后,.isdecimal返回False
# .isnumeric还支持中文数字,若将变量值改为中文数字,
# .isnumeric依然返回True,其他两种方法都返回False。

3.判断字符串是否以指定字符开始和结束

python 复制代码
hello_str = "hello world"
# 1.判断是否以指定字符串开始
print(hello_str.startswith("hello")) # 输出:True

# 2.判断是否以指定字符串结束
print(hello_str.endswith("world")) # 输出:True

4.查找指定字符串首次出现的位置

python 复制代码
# 3.查找指定的字符串首次出现的位置)
print(hello_str.find("o")) # 输出:4
print(hello_str.find("abc")) # 输出:-1
# index方法也可以查找指定的字符串所在位置
# index如果指定的字符串不存在会报错
# find查找如果指定的字符串不存在返回负1(-1)

5.替换字符串

python 复制代码
# 4.替换字符串
print(hello_str)
print(hello_str.replace("world","python")) # 输出 hello python
# replace方法执行完成后,会返回一个新的字符串,不会修改原有的字符串内容。
print(hello_str) # 输出 hello world

字符串方法详细内容参考:

python基础语法学习: 字符串 (string) 方法汇总_python 字符串方法大全-CSDN博客

相关推荐
开源量化GO1 小时前
近期量化实现:API 数据、策略逻辑和交易执行要连成一条线
人工智能·python
小柯南敲键盘1 小时前
跨马翻译:跨境电商批量图片翻译与视频字幕工具推荐
人工智能·python·音视频
前端_刘师兄1 小时前
FAE工程师学习路线-进程
前端
执子念的飞鱼1 小时前
浏览器直接预览 Pages、Numbers、Keynote:iWork 格式真正难在哪
前端·javascript
alloc1 小时前
从延迟聚合到可解释诊断:MetricKit 的原理与工程化实践
前端
颜进强1 小时前
06 - OpenSpec change 从模糊想法到完整契约:new change / explore / propose 三连
前端·后端·ai编程
Cache技术分享1 小时前
499. Java 反射 - 获取类型上的注解
前端·后端
用户921080262861 小时前
左侧历史对话模块:使用 Conversations 搭建会话入口
前端
用户69371750013842 小时前
9531 款 AI 工具流量真相:当 90% 的访问涌向 100 个平台,普通创业者还有机会吗?
前端·后端