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

python中format

作者:花小泽ノ   发布日期:2026-02-10   浏览:32

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

# 使用命名参数
person = {'name': 'Bob', 'age': 25}
formatted_string_with_named_args = "My name is {name} and I am {age} years old.".format(**person)
print(formatted_string_with_named_args)  # 输出: 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

# 对齐和填充
text = "hello"
formatted_text = "{:^10}".format(text)  # 居中对齐,总长度为10
print(formatted_text)  # 输出:   hello   

# 填充字符
formatted_text_with_fill = "{:*^10}".format(text)  # 使用 * 填充并居中对齐
print(formatted_text_with_fill)  # 输出: **hello***

以上代码展示了 Python 中 format 方法的多种用法,包括简单的字符串格式化、使用索引和命名参数、格式化数字以及对齐和填充等。

上一篇:python爬虫框架

下一篇:python sys.argv

大家都在看

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

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

Laravel 中文站