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

python中format函数的用法

作者:绝朢╭ァ   发布日期:2026-02-01   浏览:37

# 示例代码:使用 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.

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

# 对齐和填充
formatted_string = "{:>10}".format("hello")  # 右对齐,总宽度为10
print(formatted_string)  # 输出:      hello

formatted_string = "{:<10}".format("hello")  # 左对齐,总宽度为10
print(formatted_string)  # 输出: hello     

formatted_string = "{:^10}".format("hello")  # 居中对齐,总宽度为10
print(formatted_string)  # 输出:   hello   

formatted_string = "{:*^10}".format("hello")  # 居中对齐,用 * 填充,总宽度为10
print(formatted_string)  # 输出: **hello***

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

解释说明:

  • format 函数用于将指定的值插入到字符串中的占位符 {} 中。
  • 占位符可以是空的(如 {}),也可以包含索引(如 {0}, {1})或关键字(如 {name}, {age})。
  • 可以通过格式说明符来控制输出的格式,例如小数点后保留几位、对齐方式等。

上一篇:callable在python中的用法

下一篇:python mkdir

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

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

Laravel 中文站