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

python format()函数的功能和用法

作者:断念已残   发布日期:2026-03-04   浏览:117

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

# 基本用法:按位置传递参数
formatted_string = "Hello, {}!".format("World")
print(formatted_string)  # 输出: Hello, World!

# 使用多个参数
name = "Alice"
age = 30
greeting = "My name is {} and I am {} years old.".format(name, age)
print(greeting)  # 输出: My name is Alice and I am 30 years old.

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

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

# 格式化数字
number = 1234.56789
formatted_number = "The number is {:.2f}".format(number)
print(formatted_number)  # 输出: The number is 1234.57

# 对齐和填充
aligned_text = "{:>10}".format("hello")
print(aligned_text)  # 输出:      hello

# 使用变量作为格式化参数
width = 10
aligned_text_var = "{:^{}}".format("hello", width)
print(aligned_text_var)  # 输出:   hello   

# 解释说明:
# 1. `format()` 函数用于将指定的值插入到字符串中的占位符位置。
# 2. 占位符可以是简单的 `{}`,也可以带有索引或关键字。
# 3. 可以通过格式说明符(如 `:.2f`)来控制输出的精度和格式。
# 4. 支持对齐和填充字符的设置,例如 `:<`, `:>`, `:^` 分别表示左对齐、右对齐和居中对齐。

上一篇:python trim

下一篇:python flet

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

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

Laravel 中文站