目录
-
- [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)
作用是 打印变量的"原始表示",包括引号和转义字符。