温馨提示×

python的fstring的用法是什么

小亿
85
2024-08-23 02:20:29
栏目: 编程语言

fstring是Python3.6及以上版本引入的一种新的字符串格式化方法,它使用类似于JavaScript的模板字符串的语法,以在字符串中插入变量和表达式。

fstring的用法非常简单和直观,只需在字符串前加上字母"f"或"F",然后在字符串中使用大括号{}来包裹要插入的变量或表达式。例如:

name = "Alice"
age = 30
height = 170.5

# 使用fstring格式化字符串
message = f"My name is {name}, I am {age} years old and my height is {height} cm."
print(message)

输出结果为:

My name is Alice, I am 30 years old and my height is 170.5 cm.

使用fstring不仅简洁方便,而且性能更好,推荐在Python3.6及以上版本中使用fstring来进行字符串格式化。

0