网站首页 > 技术文章 正文

Python 3.6 中引入了 f-string语法,提供了一种简洁直观的方法来将表达式和变量直接嵌入到字符串中进行字符串格式化,f -string背后的想法是使字符串插值更简单。
要创建 f -string,在字符串前加上字母 “f”即可,与字符串本身的格式化方式与使用 str. format()的方式非常相似。f -string提供了一种简洁方便的方法,使得代码看起来更简洁。
使用 f-string 打印变量
以下示例,我们使用花括号在f-string中使用变量值,直接将变量值嵌入到字符串中进行打印输出。
# Python3 program introducing f-string
val = 'Hello'
print(f"变量值为:{val}.")
变量值为:Hello.
name = '码路刺客'
age = 32
print(f"Hello, My name is {name} and I'm {age} years old.")
Hello, My name is 码路刺客 and I'm 32 years old.
使用 f-string 打印日期
以下示例中,我们使用 Python 中的 datetime 模块和 f-string 打印了今天的日期。首先导入 datetime 模块,然后我们使用 f-ting 打印日期。在 f-string 的花括号中分配了当前日期,% B、% d 和 % Y 分别代表完整的月份、天和年份。
# Prints today's date with help
# of datetime library
import datetime
today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")
November 26, 2024
f-string比两种常用的字符串格式化机制(% formatting 和 str. format() )更快。
f-string中的单引号和双引号
在 Python 中,要在 f-string中使用任何类型的引号,我们必须确保表达式中使用的引号与 外部 f-string使用的引号不同。
# 输出单引号
print(f"'Hello World'")
# 输出双引号
print(f"""Hello"My"World""")
# 输出单引号
print(f'''Hello'My'God''')
'Hello World'
Hello"My"World
Hello'My'God
使用 f-Strings 计算表达式
在 Python 中,我们也可以使用 f-string来计算表达式。我们必须将表达式写在 f-string的花括号内,计算结果将如下面代码的输出。
english = 78
maths = 56
chinese = 85
print(f"各科总分为: {english + maths + chinese}")
各科总分为: 219
使用 f-string 时报错
在 Python的 f-string 中,反斜杠不能直接用于格式字符串。
print(f"换行符的ascii码: {ord('\n')}")
File "C:\Users\69570\AppData\Local\Temp/ipykernel_19724/3445930297.py", line 1
print(f"换行符的ascii码: {ord('\n')}")
^
SyntaxError: f-string expression part cannot include a backslash
# 变通
newline = ord('\n')
print(f"换行符的ascii码: {newline}")
换行符的ascii码: 10
使用 f-string 打印花括号
如果我们想在 f-string 的输出中显示花括号,那么我们必须在 f-string 中使用双花括号。请注意,对于每一对单花括号,我们需要像下面的代码中那样输入双花括号。
# Printing single braces
print(f"{{Hello, World}}")
# Printing double braces
print(f"{{{{Hello, World}}}}")
{Hello, World}
{{Hello, World}}
使用 f-string 输出字典键值
var = { 'Id': 112,'Name': 'Harsh'}
print(f"Id of {var['Name']} is {var['Id']}")
Id of Harsh is 112
使用 f-string 输出数值精度
num = 3.14159
formatted = f"{num:.2f}"
print(formatted) # Output: 3.14
使用 f-string 动态拼装JSON
name = "Alice"
age = 30
json_data = f'{{ "name": "{name}", "age": {age} }}'
print(json_data)
Output:
{ "name": "Alice", "age": 30 }
在 Python 3.6 中引入 f-string 之前,您可以使用 str. format()方法或使用 % formatting(旧式格式)来格式化字符串.
name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)
Output:
My name is Alice and I am 30 years old.

猜你喜欢
- 2024-12-13 Python数据类型字符串的几种表示形式
- 2024-12-13 python 基础语法详解(入门必读)
- 2024-12-13 轻松掌握!Python 基本语法与核心数据类型全解析
- 2024-12-13 Python注释方式有哪些
- 2024-12-13 Word 神器 python-docx
- 2024-12-13 万字干货,Python语法大合集,一篇文章带你入门
- 2024-12-13 Python之open()函数
- 2024-12-13 编程语言python:数据类型
- 2024-12-13 Python基础语法到高级概念
- 2024-12-13 Python字符串单引号('...')和双引号("...")的区别
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)