python 移除字符串尾部的数字方法

yipeiwu_com5年前Python基础

今天在下脚本的时候遇到一个问题,比如有这样的一个字符串 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 移除字符串尾部的数字方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python每天定时运行某程序代码

思路:利用time函数返回的时间字符串与指定时间字符串做比较,相等的时候执行对应的操作。不知道大家的思路是什么,感觉这样比较耗CPU。。。。 此处设置为15:30:10 输出相应内容,需...

python实现关闭第三方窗口的方法

背景 最近在测试一款软件的关闭第三方窗口的功能,感觉实现应该挺简单的。所以就尝试了。由于说它的实现是靠c++实现的,本人对c++实在不在行,但是python的第三方库实际上是封装了一套w...

使用matplotlib绘制图例标签中带有公式的图

使用matplotlib绘制图例标签中带有公式的图

我就废话不多说了,直接上代码吧! import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,2*np....

无法使用pip命令安装python第三方库的原因及解决方法

无法使用pip命令安装python第三方库的原因及解决方法

再dos中无法使用pip,命令主要是没有发现这个命令。我们先找到这个命令的位置,一般是在python里面的Scripts文件夹里面。我们可以把dos切换到对应的文件夹,再使用pip命令就...

对Python3中的input函数详解

对Python3中的input函数详解

下面介绍python3中的input函数及其在python2及pyhton3中的不同。 python3中的ininput函数,首先利用help(input)函数查看函数信息: 以上信息...