今天在下腳本的時候遇到一個問題,比如有這樣的一個字符串 t = "book123456",想把尾部的數字全部去掉,只留下“book”,自己用正則試了下,是實現了,但速度不是很快,于是問了一下同事,他給的解決的方法確實很簡潔,也讓自己長了知識點,如下:
1
2
3
|
import string t.rstrip(string.digits) |
這樣就全部將數字移除了,順便將string這個模塊看了下文檔,也有一定的收獲。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
>>> 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相互轉化:
1
2
3
4
|
>>> string.atof( "1.23" ) 1.23 >>> string.atof( "1" ) 1.0 |
轉換的時候還可以制定進制的轉化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
>>> 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,然后將每個字符串的首字母大寫
1
2
3
4
5
6
7
8
9
|
>>> 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()方法來實現
1
2
3
4
5
6
7
|
>>> replist = string.maketrans( "123" , "abc" ) >>> replist1 = string.maketrans( "456" , "xyz" ) >>> s = "123456789" >>> s.translate(replist) 'abc456789' >>> s.translate(replist1) '123xyz789' |
以上這篇python 移除字符串尾部的數字方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/lulongfei172006/article/details/51744505