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

python 格式化字符串

作者:浮云过影   发布日期:2025-10-29   浏览:30

# 示例代码:Python 格式化字符串

# 使用 % 操作符进行格式化
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.7 和 Python 3.x 中推荐的格式化方法,使用 {} 作为占位符,并通过 .format() 方法传递参数。
  3. f-string:这是 Python 3.6 引入的新特性,使用 f 前缀和花括号 {} 来嵌入表达式,语法简洁且性能更好。

上一篇:complex函数python

下一篇:python集合的基本操作

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

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

Laravel 中文站