Files
Python_CookBook_repo/2.字符串和文本/15.给字符串中的变量做插值处理.py
2025-09-10 16:12:45 +08:00

44 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
if __name__ == "__main__":
# 一般来说,我们用{}和format函数对字符串进行插值
s = "{name} has {n} messages"
s1 = s.format(name="Sam", n=10)
print(s1)
# 当然如果你想偷懒,也可以这样:
name = "Sam"
n = 10
s2 = s.format_map(vars())
print(s2)
# 在上面这段代码中vars函数会从堆栈里自动寻找变量名称的值
# vars还能解析类实例
class INFO:
def __init__(self, name, n):
self.name = name
self.n = n
info = INFO(name, n)
s3 = s.format_map(vars(info))
print(s3)
# 爽吗?确实爽,但是有一个缺点,在填充值缺失的时候这玩意儿会报错
try:
s4 = s.format(name=name)
except KeyError:
print("少参数")
# 我们可以定义一个类的__missing__方法来防止出现这种情况
class Safe_Sub(dict):
def __missing__(self, key):
return '{'+ key +'}'
del n
print(s.format_map(Safe_Sub(vars())))
# 如果经常操作,那么可以把这个功能藏在函数里,同时从当前调用的堆栈里找到变量(我反正不建议这么干,不过得知道)
def sub(text):
# 不代码里tmd堆栈这是手贱行为可能导致各种bug除非有必要的理由否则不要这么做
return text.format_map(Safe_Sub(sys._getframe(1).f_locals))
name = "Suka"
print(sub(s))