这篇文章主要介绍string模块中几个典型方法的用法,涉及的方法有:atof()、atoi()、maketrans()和capwords()。其中前三个方法在Python3.6中已经不适用了,四个方法均适用于Python2。
(1)string.atof(x):将字符串转换为浮点数字
Python2中代码如下所示:
print string.atof("5.23")
print string.atof("2")
结果:
1.23
1.0
python3中可直接用float()代替改函数的功能,如下:
print(float(5.23))
print(float(2))
结果:
5.23
2.0
(2)string.atoi(x,[base=num]):将字符串转化为整形数字,base用于指定进制
python2中代码如下所示:
print string.atoi("20")
print string.atoi("20",base=10)
print string.atoi("20",base=16)
print string.atoi("20",base=8)
结果:
20
20
32
16
python3中可以用int()代替函数的功能,如下:
print(int("20"))
结果:
20
(3)string.maketrans(a,b):创建一个a到b的转换表,可以使用translate()方法来调用
import string
defe = string.maketrans("123", "xzw")
defe1 = string.maketrans("456", "lzq")
s = "123456"
print s.translate(defe)
print s.translate(defe1)
结果:
'xzw456'
'123lzq'
(4)string.capwords(a, sep=None):以sep为分隔符,分割字符串a
import string
print string.capwords("This is a book and that is a pen")
print string.capwords("This is a book and that is a pen", sep=" ")
print string.capwords("This is a book and that is a pen", sep="a")
print string.capwords("This is a book and that is a pen", sep="o")
结果:
This Is A Book And That Is A Pen
This Is A Book And That Is A Pen
This is a book aNd thaT is a pen
This is a booK and that is a pen