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

python format函数

作者:最终一次颓废   发布日期:2025-05-05   浏览:44

# 示例代码:使用 format 函数格式化字符串

# 基本用法
name = "Alice"
age = 30
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.

# 指定位置参数
formatted_string = "My name is {1} and I am {0} years old.".format(age, name)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 使用关键字参数
formatted_string = "My name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string)  # 输出: My name is Bob and I am 25 years old.

# 格式化数字
pi = 3.141592653589793
formatted_string = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_string)  # 输出: The value of pi is approximately 3.14

# 对齐和填充
formatted_string = "{:<10} | {:^10} | {:>10}".format("left", "center", "right")
print(formatted_string)  # 输出: left       |   center   |       right

解释说明:

  • format 函数用于将指定的值插入到字符串中。
  • {} 是占位符,表示将在此处插入值。
  • 可以通过位置参数、关键字参数或格式化选项来控制输出格式。
  • :.2f 表示保留两位小数。
  • <, ^, > 分别表示左对齐、居中对齐和右对齐。

上一篇:python打开文件

下一篇:python for 循环

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

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

Laravel 中文站