<返回更多

Python中f-string用法

2023-04-06  今日头条  千里马的驴
加入收藏

f-string是Python/ 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 Approximately {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. 注意事项:

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>