Python基於template實現字串替換

2022-09-27 03:54:12 字數 1100 閱讀 2778

下面介紹使用python字串替換的方法;

1. 字串替換

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

template = "hello %s , your website is %s " % ("大cc","")

print(template)

也可使用format函式完成:

template 程式設計客棧= "hello , your website is ".format("大cc","")

print(template)

注:該方法適用於變程式設計客棧量少的單行字串替換;

2. 字串命名格式化符替換

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

template = "hello %(name)s ,your name is %(name), your website is %(message)s" %

print(template)

使用format函式的語法方式:

template = "hello , your name is , your website is ".format(name="大cc",message="")

print(template)

注:適用相同變數較多的單行字串替換;

3.模版方法替換

使用string中的template方法;

通過關鍵字傳遞引數:

from string import template

temptemplate = template("hello $name ,your website is $message")

print(temptemplate.substitute(name='大cc',message='程式設計客棧15.com'))

通過字典傳遞參yydskcm數:

from string import template

temptemplate = template("there $a and $b")

d=print(temptemplate.substitute(d))

本文標題: python基於template實現字串替換

本文位址:

WPF樣式(Style)與模板(Template)

一 wpf樣式 類似於web應用程式中的css,在wpf中可以為控制項定義統一的樣式 style 樣式屬於資源的一種,例如為button定義統一的背景顏色和字型 1 2 9 10 11 button a12 button b13 從執行的結果上來看 這種樣式,類似於css中的型別選擇器,為某種型別定...

Django技術詳解(四)開發template

templates,在django其實是乙個乙個的html檔案,它使用了django模板語言 django template language,dtl 也可以第三方模板 如jinja2 步驟如下 1 在應用的根目錄下建立名叫templates的目錄 2 在該目錄下建立html檔案 3 在views....

基於python的爬蟲

本次初學,參考的資料見 功能主要是抓取韓寒的部落格內容,以及儲存 到 hanhan的資料夾中,執行環境實在linux下的。見 具體 如何 usr bin env python coding utf 8 import urllib import time url 60 con urllib.urlop...