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

python format用法

作者:殘月殺手   发布日期:2025-09-13   浏览:64

# 示例代码:使用 format 方法格式化字符串

# 1. 基本用法
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.

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

# 3. 使用关键字参数
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.

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

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

formatted_string = "{:^10}".format("center")
print(formatted_string)  # 输出:   center   

formatted_string = "{:*^10}".format("center")
print(formatted_string)  # 输出: **center**

# 6. 使用变量作为格式化参数
width = 10
precision = 4
value = 1234.5678
formatted_string = "The value is {:{width}.{precision}f}".format(value, width=width, precision=precision)
print(formatted_string)  # 输出: The value is    1234.5678

解释说明:

  • format 方法是 Python 中用于字符串格式化的强大工具。
  • 可以通过位置参数、关键字参数或混合使用两者来插入和格式化变量。
  • 支持多种格式化选项,如对齐、填充、精度控制等。
  • {} 是占位符,{} 中的内容可以指定索引、变量名或格式化选项。

上一篇:python numba

下一篇:python静态方法和类方法的区别

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

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

Laravel 中文站