Python中如何格式化字符串?
时间: 2024-06-01 13:06:35 浏览: 129
在Python中,可以使用格式化字符串来将变量或者表达式嵌入到字符串中。格式化字符串的方式有多种,下面是其中三种常用的方式:
- 使用百分号 % 进行格式化
可以使用 % 操作符将变量或者表达式嵌入到字符串中,例如:
name = 'Jack'
age = 18
print("My name is %s, and I'm %d years old." % (name, age))
这里的 %s 表示将字符串类型的变量或者表达式嵌入到字符串中,%d 表示将整数类型的变量或者表达式嵌入到字符串中。
- 使用 format 方法进行格式化
可以使用 format 方法将变量或者表达式嵌入到字符串中,例如:
name = 'Jack'
age = 18
print("My name is {}, and I'm {} years old.".format(name, age))
这里的 {} 表示占位符,format 方法会将传入的参数依次填充到占位符中。
- 使用 f-string 进行格式化
f-string 是Python3.6引入的一种字符串格式化方式,可以在字符串前加上 f 或者 F,然后在字符串中使用 {} 来嵌入变量或者表达式,例如:
name = 'Jack'
age = 18
print(f"My name is {name}, and I'm {age} years old.")
这里的 {} 表示占位符,f-string 会将花括号内的变量或者表达式求值并替换成对应的值。
阅读全文
相关推荐
















