Python 高效移除字符串尾部数字及 string 模块实用技巧

七月
七月
发布时间:2026-10-13| 5人浏览过
原创

本文介绍利用 Python string 模块移除字符串尾部数字的高效方法,并详解 string 模块中数字转换、大小写处理及字符映射等实用功能,帮助开发者简化字符串操作。

在编写脚本时,常需处理如 t = "book123456" 这类字符串,目标是仅保留前缀文字 "book" 而去除尾部数字。虽然正则表达式能实现此功能,但性能往往不佳。经同事建议,采用更简洁且高效的方法解决该问题,具体实现如下:

import string

t.rstrip(string.digits)

通过上述方式即可彻底移除尾部数字。此外,查阅 string 模块文档可获得更多相关收益与技巧。

>>> import string
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
'\t\n\x0b\x0c\r '
>>>

string 模块还支持字符串与 int、float 类型之间的相互转换,示例如下:

>>> string.atof("1.23")
1.23
>>> string.atof("1")
1.0

在执行转换时,还可以指定具体的进制格式进行转换操作。



>>> string.atoi("20")
20
>>> string.atoi("20",base=10)
20
>>> string.atoi("20",base=16)
32
>>> string.atoi("20",base=8)
16
>>> string.atoi("20",base=2)
Traceback (most recent call last):
 File "", line 1, in <module>
 File "/usr/lib64/python2.6/string.py", line 403, in atoi
  return _int(s, base)
ValueError: invalid literal for int() with base 2: '20'
>>> string.atoi("101",base=2)
5
>>> string.atoi("101",base=6)
37

capwords(s, sep = None)函数以 sep 作为分隔符对字符串 s 进行分割,随后将每个分割后的字符串首字母转换为大写。

>>> string.capwords("this is a dog")
'This Is A Dog'
>>> string.capwords("this is a dog",sep=" ")
'This Is A Dog'
>>> string.capwords("this is a dog",sep="s")
'This is a dog'
>>> string.capwords("this is a dog",sep="o")
'This is a doG'
>>>

maketrans(s, r)函数用于创建从 s 到 r 的字符转换映射表,随后可利用 translate()方法执行实际的字符替换操作。

>>> replist=string.maketrans("123","abc")
>>> replist1=string.maketrans("456","xyz")
>>> s="123456789"
>>> s.translate(replist)
'abc456789'
>>> s.translate(replist1)
'123xyz789'

以上关于 Python 移除字符串尾部数字的方法及 string 模块的应用即为全部内容,希望能为读者提供参考,并期待大家的支持。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。