Pythoner集中营Python精选零基础学Phyton

字符串

2015-07-20  本文已影响175人  LittleWizard

使用字符串

格式化字符串
>>> format = "Hello, %s. %s enough for ya"
>>> values = ('world', 'hot')
>>> print format % values #Hello, world. Hot enough for ya

模板字符串
>>> from string import Template
>>> s = Template('$x, glorious $x')
>>> s.substitute(x = 'slurm') #'slurm, glorious slurm'
注:如果替换的字段是单词的一部分,那么参数名就必须要括起来
>>> s = Template("It's ${x}tatic)

字符串格式化

>>> from math import pi
>>> '%10f' % pi               #字段宽为10
>>> '%10.2f' % pi             #字段宽10,精度为2
>>> '%.2f' % pi               #精度宽度为2
>>> '%.5s' % 'Guido van Rossum'             #保留字符串5位
>>> '%.*s' % (5, 'Guido van Rossum')        #元组中读出参数
>>> '%010.2f' % pi       #字段宽度为10,不足位数用0填补
>>> '%-10.2f' % pi       #字段宽度为10,精度为2,左对齐
>>> '% 5d' % -10         #字段宽度为5,前面的空格用于放置-号
>>> '%+5d' % -10         #字段的宽度为5,符号位为-

字符串方法
>>> import string
>>> string.digits #0-9数字字符串
>>> string.letters #所有字母的字符串
>>> string.lowercase #所有小写字母的字符串
>>> string.uppercase #所有大写字母的字符串
>>> string.printable #所有可以打印的字符的字符串
>>> string.punctuation #所有标点符号的字符串

find函数
>>> 'hello world, this is a new start'.find('hello') #在字符串中找到hello的位置
>>> title = "Monty Python's Flying Cricus"
>>> title.find('python') #在字符串中找到python的位置
>>> title.find('Python', 1) #在字符串中指定查找的起始位置
>>> title.find('Python', 1, 16) #在字符串中指定查找的范围1-16

join函数
>>> seq = ['1','2','3','4']
>>> condition = '+'
>>> condition.join(seq) #用+连接字符串列表
>>> dirs = ['','usrs','bin','env']
>>> '/'.join(dirs) #用/连接地址字符串

lower函数
>>> str = 'HELLO WORLD'
>>> str.lower() #返回字符串的小写

replace函数
>>> "it's a new test".replace('new', 'old') #将字符串中与new匹配的字符串替换为old

split函数
>>> seq = 'abcdef'
>>> seq.split() #将字符串以+为条件分割为一个列表

strip函数
>>> ' hello world '.strip() #将字符串两侧的空格删除
>>> '#!#!get a high #! score#!#!'.strip('#!') #将字符串两侧的#!删除

translate函数
>>> from string import maketrans
>>> table = maketrans('cs', 'kz') #创建转换表
>>> 'this is side'.translate(table) #转换
注:与replace相比,translate函数只处理单个字符

capwords函数
>>> print(string.capwords("hello world", " ").replace(" ", "-")) #将字符串每个单词首字母大写并以-分割

上一篇 下一篇

猜你喜欢

热点阅读