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

python字符串格式化

作者:嗜血之舞   发布日期:2025-09-18   浏览:89

# Python 字符串格式化示例

# 1. 使用 % 操作符进行字符串格式化
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.

# 2. 使用 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.

# 3. 使用 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. % 操作符:这是最早的字符串格式化方法,使用 %s 表示字符串,%d 表示整数。虽然这种方法仍然可用,但推荐使用更现代的方法。
  2. str.format() 方法:这是 Python 2.7 和 Python 3.x 中常用的方法,通过大括号 {} 占位符来插入变量值。
  3. f-string:这是从 Python 3.6 开始引入的最简洁和高效的字符串格式化方法,直接在字符串前加 fF,并在大括号中放入表达式即可。

上一篇:python word

下一篇:python os.path

大家都在看

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 中文站