print(f“{s!r}“)解释

目录

    • [1️⃣ 第一行](#1️⃣ 第一行)
    • [2️⃣ 第二行:f-string](#2️⃣ 第二行:f-string)
    • [3️⃣ `!r` 的作用](#3️⃣ !r 的作用)
    • [4️⃣ `repr()` 和 `str()` 的区别](#4️⃣ repr()str() 的区别)
    • [5️⃣ 你的代码输出](#5️⃣ 你的代码输出)
    • [6️⃣ f-string 中的三个常见转换](#6️⃣ f-string 中的三个常见转换)
    • [7️⃣ 常见使用场景(调试)](#7️⃣ 常见使用场景(调试))

这段 Python 代码主要演示 f-string 中的 !r 转换标志 的作用。我们逐步解释:

python 复制代码
s = "hello world!\n"
print(f"{s!r}")

1️⃣ 第一行

python 复制代码
s = "hello world!\n"

字符串 s 的内容是:

复制代码
hello world!

但结尾有一个 换行符 \n

实际字符串内容是:

复制代码
hello world!\n

其中 \n 表示换行。


2️⃣ 第二行:f-string

python 复制代码
print(f"{s!r}")

这里使用了 f-string(格式化字符串)

基本格式:

python 复制代码
f"{expression}"

可以在 {} 中放变量或表达式。


3️⃣ !r 的作用

!r 表示:

复制代码
对表达式调用 repr()

也就是:

python 复制代码
repr(s)

所以:

python 复制代码
f"{s!r}"

等价于:

python 复制代码
repr(s)

4️⃣ repr()str() 的区别

Python 有两种字符串表示方式:

函数 用途
str() 给用户看的
repr() 给开发者看的(更精确)

例子:

python 复制代码
s = "hello world!\n"

print(s)

输出:

复制代码
hello world!

因为 \n 变成了真实换行。


如果:

python 复制代码
print(repr(s))

输出:

复制代码
'hello world!\n'

注意:

  • 引号
  • \n 被显示出来

5️⃣ 你的代码输出

python 复制代码
s = "hello world!\n"
print(f"{s!r}")

输出:

复制代码
'hello world!\n'

原因:

复制代码
f"{s!r}" → repr(s)

6️⃣ f-string 中的三个常见转换

Python f-string 有三个常用转换:

写法 等价
{x} str(x)
{x!s} str(x)
{x!r} repr(x)
{x!a} ascii(x)

例子:

python 复制代码
s = "hello\n"

print(f"{s}")   # hello (换行)
print(f"{s!s}") # hello (换行)
print(f"{s!r}") # 'hello\n'

7️⃣ 常见使用场景(调试)

!r 非常适合调试

python 复制代码
name = "Tom\n"

print(f"name = {name!r}")

输出:

复制代码
name = 'Tom\n'

可以看到隐藏字符。


一句话总结

python 复制代码
{s!r}

等价于

python 复制代码
repr(s)

作用是 打印变量的"原始表示",包括引号和转义字符

相关推荐
IsSh9nj6q12 分钟前
Python全栈应用搭建神器magic-dash .新版本介绍
开发语言·python·dash
Cachel wood33 分钟前
hands-on-modern-rl:动手学强化学习策略梯度reinforce
开发语言·python
蓝斯4971 小时前
一碰即传,重构跨设备文件分享体验
开发语言·python·重构
宁风NF1 小时前
JavaScript:内存、垃圾回收、性能优化
开发语言·前端·javascript·学习·性能优化·es6
ShuiShenHuoLe1 小时前
Go html/template 使用入门
开发语言·golang·html
geovindu1 小时前
java: Gale-Shapley Algorithm
java·开发语言·后端·算法
冻柠檬飞冰走茶2 小时前
PTA基础编程题目集 7-34 通讯录的录入与显示(C语言实现)
c语言·开发语言·数据结构·算法
星核0penstarry2 小时前
DeepSeek-V4-Flash 正式公测:大模型行业进入「极速平价普惠时代」
java·开发语言·人工智能
老洋葱Mr_Onion2 小时前
【C++】高精度模板
开发语言·c++·算法