Python中推荐使用f-string进行字符串格式化,因其简洁高效;其次是str.format()方法,适用于较复杂格式控制;%格式化已不推荐用于新项目;Template字符串则适合安全敏感场景。

Python中字符串格式化有多种方法,每种都有其适用场景和优势。下面整理几种常用的方式,帮助你根据实际情况选择合适的方法。
这是最早期的字符串格式化方式,类似于C语言中的printf风格。
语法:使用%操作符,配合占位符如%s(字符串)、%d(整数)、%f(浮点数)等。
示例:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# 输出:My name is Alice and I am 25 years old.
说明:简单直接,但可读性和扩展性较差,不推荐在新项目中使用。
立即学习“Python免费学习笔记(深入)”;
从Python 2.6开始引入,比%格式化更灵活强大。
语法:使用字符串的format()方法,通过{}占位。
示例:
print("My name is {} and I am {} years old.".format(name, age))
print("My name is {0} and I am {1} years old. Yes, {0}!".format(name, age))
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
优点:支持位置参数、关键字参数、重复使用变量,格式控制也更丰富,比如{:.2f}控制小数位数。
从Python 3.6开始引入,是目前最推荐的方式。
语法:在字符串前加f或F,直接在{}中写变量或表达式。
示例:
print(f"My name is {name} and I am {age} years old.")
print(f"Next year I'll be {age + 1} years old.")
price = 19.99
print(f"Price: ${price:.2f}")
优点:写法简洁、性能高、可读性强,支持表达式和格式修饰符。
适用于需要安全替换的场景,比如处理用户输入的模板。
用法:来自string模块的Template类,使用$符号插入变量。
示例:
from string import Template
t = Template("My name is $name and I am $age years old.")
print(t.substitute(name="Charlie", age=28))
优点:语法简单,安全性高,适合动态生成内容且防止代码注入。
基本上就这些常见的字符串格式化方法。日常开发中推荐优先使用f-string,兼顾简洁与功能。对于复杂或安全敏感场景,可考虑Template。老代码中可能还会见到%和format(),了解即可。
以上就是python字符串格式化的方法整理的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号