str

作者: cure_py | 来源:发表于2017-08-30 11:16 被阅读0次

1.format

在Python 3.0中,%操作符通过一个更强的格式化方法format()进行了增强

["{}月".format(i) for i in range(1,13)]
>>>['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']

使用位置参数

'my name is {} ,age {}'.format('hoho',18)
>>>'my name is hoho ,age 18'
li = ['hoho',18]
'my name is {} ,age {}'.format(*li)
>>>'my name is hoho ,age 18'

使用关键字参数

'my name is {name},age is {age}'.format(name='hoho',age=19)
>>>'my name is hoho,age is 19'
hash = {'name':'hoho','age':18}
'my name is {name},age is {age}'.format(**hash)

2. replace

a.replace().replace()
#encoding=utf-8  
print '中国'  
  
# 一次完成多个字符串替换  
#利用正则表达式re的sub方法  
  
import re  
def multiple_replace(text,adict):  
    rx = re.compile('|'.join(map(re.escape,adict)))  
    def one_xlat(match):  
        return adict[match.group(0)]  
    return rx.sub(one_xlat,text) #每遇到一次匹配就会调用回调函数  
  
#把key做成了 |分割的内容,也就是正则表达式的OR  
map1={'1':'2','3':'4',}  
print '|'.join(map(re.escape,map1))  
  
str='1133'  
print multiple_replace(str,map1)  

相关文章

网友评论

      本文标题:str

      本文链接:https://www.haomeiwen.com/subject/uxkulxtx.html