欢迎来到魔幻小生的博客

python之字面量插值

  • 字面量:以变量或常量给出的原始值,在程序中可以直接使用字面量。

  • 字面量插值:将变量与常量以及表达式插入的一种技术,可以避免字符串拼接问题。

字面量插值通常有以下三种方法:

格式化输出 %

% 操作符可以实现字符串格式化,属于旧式格式化输出,建议使用其它两种方法。

转换说明符 解释
%s 使用str()函数将表达式转换为字符串
%d 转换为带符号的十进制整数
%f 转换为十进制浮点数
>>> name = "Tom"
>>> age = 18
>>> height = 176.66666
>>> print('my name is %s, age is %d and height is %0.2f' % (name, age, height))

my name is Tom, age is 18 and height is 176.67

string.format()

通过format函数传值。列表通过在变量前加*来访问元素。字典通过在变量前加**来访问键值。

name = "Tom"
age = 18
height = 176.66666
list = ['Tom', 18, 176.66666]
dict = {'name':'Tom', 'age':18, 'height':176.66666}
print('my name is {}, age is {} and height is {:.2f}'.format(name, age, height))
print('my name is {0}, age is {1} and height is {2:.2f}'.format(*list))
print('my name is {name}, age is {age} and height is {height:.2f}'.format(**dict))

my name is Tom, age is 18 and height is 176.67

f-string

f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。

f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去。

name = "Tom"
age = 18
height = 176.66666
list = ["Tom", 18, 176.66666]
dict = {"name":"Tom", "age":18, "height":176.66666}

print(f'my name is {name}, age is {age} and height is {height:.2f}')
print(f'my name is {list[0]}, age is {list[1]} and height is {list[2]:.2f}')
print(f'my name is {dict["name"]}, age is {dict["age"]} and height is {dict["height"]:.2f}')

my name is Tom, age is 18 and height is 176.67
posted @   魔幻小生  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示