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

python str format

作者:嗜血苍狼   发布日期:2025-07-09   浏览:102

# 示例代码:使用 str.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_named_args = "My name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string_with_named_args)  # 输出: My name is Bob and I am 25 years old.

# 格式化数字
value = 123.456789
formatted_number = "The value is {:.2f}".format(value)
print(formatted_number)  # 输出: The value is 123.46

解释说明:

  • str.format() 是 Python 中用于格式化字符串的方法。
  • {} 是占位符,会根据传递的参数顺序或指定的索引、命名参数进行替换。
  • 可以通过索引(如 {0}, {1})来指定参数的位置。
  • 可以通过命名参数(如 {name}, {age})来提高代码的可读性。
  • 对于数字,可以使用格式化选项(如 :.2f)来控制输出的精度。

上一篇:python获取字符串长度

下一篇:python drop

大家都在看

python时间格式

python开发windows应用程序

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

python的for i in range

npm config set python

python代码简单

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

Laravel 中文站