文章詳情頁
Python字符串格式化常用手段及注意事項
瀏覽:74日期:2022-07-20 17:26:31
格式化方式1: 使用f''
使用示例
# -*- coding: utf-8 -*-# @Time : 2020/4/22 22:35# @Author : chinablue# 替換變量name = 'chinablue'# 格式化字符串res_str = f'hello {name}'print(res_str)
注意事項
%和format也是python常用的格式化字符串方式; 如果字符串中需要顯示{},則通過{{}}來轉義.格式化方式2: 使用string.Template
使用示例
# -*- coding: utf-8 -*-# @Time : 2020/4/22 22:35# @Author : chinablueimport string# 字典中的key為變量d = { 'name' : 'chinablue'}# 替換字符串可以寫成 $name 或 ${name}; 默認的定界符為$s = string.Template('hello ${name}')# 執(zhí)行字符串替換,res_str = s.substitute(d)print(res_str)
注意事項
占位符如果寫成${}時,變量和括號之間不能有空格; string.substitute()中的參數(shù),如果字符串中未提供占位符,會拋出KeyError異常; string.substitute()中的參數(shù)可以是字典或關鍵字參數(shù). 如果關鍵字參數(shù)和字典中的key重復了,關鍵字參數(shù)的取值優(yōu)先; string.safe_substitute()中的參數(shù),如果字符串中未提供占位符,不會拋異常; 通過繼承string.Template類,并覆蓋delimiter變量和idpattern變量.可以自定義字符串模板.以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
排行榜
