模板字符串(python基於template實現字符串替換)


1. 字符串替換

將需要替換的內容使用格式化符替代,后續補上替換內容:

template = "hello %s , your website is %s " % ("大JJ", "https://mp.weixin.qq.com/s/mrZdM9ZuT7VA3JXLeLTPuQ")

print(template)  # hello 大JJ , your website is https://mp.weixin.qq.com/s/mrZdM9ZuT7VA3JXLeLTPuQ 

也可使用format函數完成:【0、1可以作為標注被多個字符串替換的位置】

template = "hello {0} , your website is {1} ".format("大CC", "http://blog.me115.com")

print(template)  # hello 大CC , your website is http://blog.me115.com

2. 字符串命名格式化符替換:【適用於相同變量較多的單行字符串替換】

使用命名格式化符,這樣,對於多個相同變量的引用,在后續替換只用申明一次即可;

template = "hello %(name)s ,your name is %(name)s, your website is %(message)s" % {"name": "大CC",
                                                                                   "message": "http://blog.me115.com"}

print(template)  # hello 大CC ,your name is 大CC, your website is http://blog.me115.com

使用format函數的語法方式:

template = "hello {name} , your name is {name}, your website is {message} ".format(name="大CC",
                                                                                   message="http://blog.me115.com")
print(template)  # hello 大CC , your name is 大CC, your website is http://blog.me115.com 

3.模版方法替換

使用 string 模塊中的 Template 方法;

①通過關鍵字傳遞參數:

from string import Template

tempTemplate = Template("Hello $name ,your website is $message")

print(tempTemplate.substitute(name='大CC', message='http://blog.me115.com'))  # Hello 大CC ,your website is http://blog.me115.com

②通過字典傳遞參數:

from string import Template

tempTemplate = Template("There $a and $b")

print(tempTemplate.substitute({'a': 'apple', 'b': 'banbana'}))  # There apple and banbana

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM