python中替换字符串的几种方法
占位符替换
template = "hello %s , your website is %s " % ("大CC","http://blog.me115.com")print(template)
format函数替换
template = "hello {0} , your website is {1} ".format("大CC","http://blog.me115.com")print(template)
F字符串替换 ```python
!/usr/bin/env python3
name = ‘Peter’ age = 23
print(‘%s is %d years old’ % (name, age)) print(‘{} is {} years old’.format(name, age)) print(f’{name} is {age} years old’)
<a name="dIJSY"></a># 模板方法替换- 使用的是string类中的Template方法,- 支持通过关键字进行传值- 支持直接传字典进行自动拆包传值```pythonfrom string import TemplatetempTemplate = Template("Hello $name ,your website is $message")print(tempTemplate.substitute(name='大CC',message='http://blog.me115.com'))
from string import TemplatetempTemplate = Template("There $a and $b")d={'a':'apple','b':'banbana'}print(tempTemplate.substitute(d))
