Python中的string模块

本文介绍了Python中string模块的几个常用方法,包括atof(), atoi(), maketrans() 和 capwords() 的使用方法,并提供了Python2与Python3版本的示例对比。

       这篇文章主要介绍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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

象在舞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值