str

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)  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容