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设计】。

相关文章

Python2.5/2.6实用教程 入门基础篇

起步走 复制代码 代码如下: #! /usr/bin/python a=2 b=3 c="test" c=a+b print "execution result: %i"%c 知识点...

Python编写一个优美的下载器

Python编写一个优美的下载器

本文实例为大家分享了Python编写下载器的具体代码,供大家参考,具体内容如下 #!/bin/python3 # author: lidawei # create: 2016-...

Python中常用的8种字符串操作方法

Python中常用的8种字符串操作方法

拼接字符串 使用“+”可以对多个字符串进行拼接 语法格式: str1 + str2 >>> str1 = "aaa" >>> str2 = "b...

python计算牛顿迭代多项式实例分析

本文实例讲述了python计算牛顿迭代多项式的方法。分享给大家供大家参考。具体实现方法如下: ''' p = evalPoly(a,xData,x). Evaluates New...

Python使用sorted排序的方法小结

Python使用sorted排序的方法小结

本文实例讲述了Python使用sorted排序的方法。分享给大家供大家参考,具体如下: # 例1. 按照元素出现的次数来排序 seq = [2,4,3,1,2,2,3] # 按次数排...