Python 字符串格式化:三种常用方法详解

在 Python 中,您可以使用多种方法来格式化字符串,将变量插入到字符串中。以下是三种常用的方法:

1. 使用百分号(%)进行格式化

这种方法是比较传统的字符串格式化方法,使用 % 符号作为占位符。例如:

name = 'Alice'
age = 25
print('My name is %s and I am %d years old.' % (name, age))

输出:

My name is Alice and I am 25 years old.

% 后面的括号中,按照顺序列出要替换的变量。常见的格式化占位符有:

  • %s 表示字符串
  • %d 表示整数
  • %f 表示浮点数

2. 使用 format() 方法进行格式化

format() 方法是 Python 中更灵活的字符串格式化方法,使用花括号 {} 作为占位符。例如:

name = 'Bob'
age = 30
print('My name is {} and I am {} years old.'.format(name, age))

输出:

My name is Bob and I am 30 years old.

在字符串中使用一对花括号 {} 表示要替换的变量,然后调用 format() 方法传入要替换的变量。

3. 使用 f-string 进行格式化(Python 3.6 及以上版本)

f-string 是 Python 3.6 版本中引入的一种新的字符串格式化方法,它更加简洁易读。在字符串前面加上 f,然后在字符串中使用花括号 {} 表示要替换的变量。例如:

name = 'Charlie'
age = 35
print(f'My name is {name} and I am {age} years old.')

输出:

My name is Charlie and I am 35 years old.

小结

三种字符串格式化方法各有优劣,您可以根据实际情况选择最合适的方案。

  • 百分号格式化方法比较传统,使用较为广泛,但语法较为繁琐。
  • format() 方法更加灵活,可以进行更复杂的格式化操作。
  • f-string 是 Python 3.6 版本及以上版本提供的语法糖,更加简洁易读,是目前推荐使用的格式化方法。
Python 字符串格式化:三种常用方法详解

原文地址: https://www.cveoy.top/t/topic/mznZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录