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

python 字符串占位符

作者:旭旭移日   发布日期:2025-04-14   浏览:74

# 使用 % 操作符的字符串格式化
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

# 使用 str.format() 方法
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.

# 使用 f-string (Python 3.6+)
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.

解释说明:

  1. % 操作符:这是 Python 中最早的字符串格式化方法,使用 %s 表示字符串占位符,%d 表示整数占位符。通过 % 后面跟一个元组来填充占位符。
  2. str.format() 方法:这是 Python 2.6 引入的字符串格式化方法,使用 {} 作为占位符,通过 .format() 方法传递参数来填充占位符。
  3. f-string:这是 Python 3.6 引入的格式化字符串字面量,使用前缀 fF,并在大括号中直接写变量名或表达式,更加简洁和直观。

上一篇:python id()

下一篇:python 逻辑回归

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

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

Laravel 中文站