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

python .format

作者:刀魂使者   发布日期:2026-04-14   浏览:67

# 示例代码:使用 .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_with_index = "My name is {0} and I am {1} years old. Hello, {0}!".format(name, age)
print(formatted_string_with_index)  # 输出: My name is Alice and I am 30 years old. Hello, Alice!

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

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

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

解释说明:

  • .format() 方法用于将值插入到字符串中的占位符 {} 中。
  • 可以通过位置参数、索引、关键字参数等方式指定插入的值。
  • 还可以对数值进行格式化,如保留小数位数。
  • 支持对齐和填充字符的设置,例如左对齐、右对齐等。

上一篇:python print(f)

下一篇:python init

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

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

Laravel 中文站