Python中f-string用法

f-string是/ target=_blank class=infotextkey>Python中格式化字符串的一种方式,它的语法为在字符串前面加上小写字母"f",然后在字符串中使用大括号{}来包含想要格式化的变量或表达式。下面是一些f-string的使用示例:

1. 简单的插值

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

输出:

My name is Alice and I am 30 years old.

 

2. 在f-string中使用表达式

a = 10
b = 20
print(f"The sum of {a} and {b} is {a + b}.")

输出:

The sum of 10 and 20 is 30.

 

3. 指定格式化字符串的宽度和精度

x = 3.1415926535
print(f"The value of pi is roximately {x:.3f}.")

输出:

The value of pi is approximately 3.142.

 

4. 在f-string中嵌套使用{}

name = "Alice"
age = 30
print(f"My name is {name.upper()} and I am {age} years old.n{{This is a curly brace}}")

输出:

My name is ALICE and I am 30 years old.
{This is a curly brace}

 

5. 注意事项:

  • f-string只能在Python3.6及以上版本中使用。
  • f-string中使用的表达式必须是合法的Python表达式。
  • 在f-string中嵌套使用大括号时,需要使用{{}}将大括号进行转义,否则会被解析成表达式。
胜象大百科