python中替换字符串的几种方法

  • 占位符替换

    1. template = "hello %s , your website is %s " % ("大CC","http://blog.me115.com")
    2. print(template)
  • format函数替换

    1. template = "hello {0} , your website is {1} ".format("大CC","http://blog.me115.com")
    2. 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’)

  1. <a name="dIJSY"></a>
  2. # 模板方法替换
  3. - 使用的是string类中的Template方法,
  4. - 支持通过关键字进行传值
  5. - 支持直接传字典进行自动拆包传值
  6. ```python
  7. from string import Template
  8. tempTemplate = Template("Hello $name ,your website is $message")
  9. print(tempTemplate.substitute(name='大CC',message='http://blog.me115.com'))
  1. from string import Template
  2. tempTemplate = Template("There $a and $b")
  3. d={'a':'apple','b':'banbana'}
  4. print(tempTemplate.substitute(d))