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

python的format

作者:迷失未来   发布日期:2026-07-11   浏览: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 = "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.

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

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

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

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

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

# 进制转换
number = 42
formatted_string = "Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(number)
print(formatted_string)  # 输出: Binary: 101010, Octal: 52, Hexadecimal: 2a

解释说明:

  • format 方法是 Python 中用于格式化字符串的一种方式。它允许你将变量插入到字符串中的指定位置。
  • {} 是占位符,format 方法会根据传递的参数依次填充这些占位符。
  • 你可以通过位置参数、关键字参数或格式说明符来控制输出的格式。
  • 格式说明符可以用来控制数值的精度、对齐方式、填充字符等。

上一篇:python re match

下一篇:python paramiko模块

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

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

Laravel 中文站