戴宇轩 发表于 2015-3-22 15:29:03

<标准库> string模块【原创】

本帖最后由 戴宇轩 于 2015-3-22 15:49 编辑

string模块中的很多函数与字符串对象的方法类似, 这里就不介绍了

#########################

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 # ASCII符号
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace # 空白字符
'\t\n\x0b\x0c\r '

string.atof(s)
将字符串转为浮点型数字>>> string.atof('3.14')
3.14
>>> string.atof('128')
128.0

string.atoi(s, base=10)
将字符串s转为整型数字, base指定数字的进制, 默认为十进制>>> string.atoi('1024')
1024
>>> string.atoi('52', base=10)
52
>>> string.atoi('FF', base=16)
128
>>> string.atoi('80', base=8)
64
>>> string.atoi('110', base=2)
6
>>> string.atoi('21', base=6)
13

string.capwords(s, sep=' ')
将字符串中开头和sep后面的字母变成大写>>> 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'

string.maketrans(s, r)
创建一个s到r的字典, 可以使用字符串对象的translate()方法来使用>>> tsl_1 = string.maketrans('1234', 'abcd')
>>> tsl_2 = string.maketrans('4569', 'xyzt')
>>> s = '123456789'
>>> s.translate(tsl_1)
'abcd56789'
>>> s.translate(tsl_2)
'123xyz78t'
>>> tsl_1
{'1': 'a', '3': 'c', '2': 'b', '4': 'd'}
>>> tsl_2
{'5': 'y', '9': 't', '4': 'x', '6': 'z'}

marszx 发表于 2015-5-23 00:08:16

为什么有些用不了是不是我的版本太低了3.4.2 的:sad

双枪李向阳 发表于 2016-4-25 23:52:50

{:10_256:}

yunzhongzhuhuo 发表于 2016-8-19 10:00:42

{:9_232:}

dh89 发表于 2016-11-17 09:21:41

学习学习

wweewwee 发表于 2017-1-15 14:43:06

楼主的是什么版本的啊??

tonytsai 发表于 2019-11-29 17:21:26

string.atof(s),这个我怎么用不了?
页: [1]
查看完整版本: <标准库> string模块【原创】