Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python中格式化字符串的几种方法

作者:冷空气来袭   发布日期:2026-07-16   浏览:32

# 方法1: 使用 % 操作符 (旧式格式化)
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 方法2: 使用 str.format() 方法 (新式格式化)
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 方法3: 使用命名参数
formatted_string = "My name is {n} and I am {a} years old.".format(n=name, a=age)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 方法4: 使用 f-string (Python 3.6+)
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 方法5: 使用 format 函数与索引
formatted_string = "My name is {0} and I am {1} years old.".format(name, age)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

上一篇:python集合和列表的区别

下一篇:python 二维码

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站