在学习 Python 的过程中,你可能会好奇:print()
到底会不会输出字符串的引号?在普通 Python 和 Jupyter Notebook (.ipynb
) 里有区别吗?这篇笔记帮你系统整理,适合复习!
🌟 1️⃣ 在普通 Python 中 print()
的行为
基本用法
print("hello")
print('hello')
输出:
hello
hello
✅ 结论:print()
不会打印字符串的引号,只输出内容。
🌟 2️⃣ 如何让 print()
打印出引号?
如果你希望引号出现在输出中,有几种方法:
✅ 方法 1:直接在字符串内容中写上引号
print('"hello"')
print("'hello'")
输出:
"hello"
'hello'
✅ 方法 2:使用 repr()
函数
repr()
返回字符串的“官方表现形式”,包括引号。
s = "hello"
print(repr(s))
输出:
'hello'
如果字符串内部含有单引号,它会用双引号:
s = "he'llo"
print(repr(s))
输出:
"he'llo"
🌟 3️⃣ 在 Jupyter Notebook 里的区别
Jupyter Notebook 有一个特别的行为:
- 如果你在 最后一行直接写表达式(而不是用
print()
),Notebook 会自动输出repr()
的结果。
例如:
"hello"
输出:
'hello'
"he'llo"
输出:
"he'llo"
✅ 如果你用 print()
,和普通 Python 一样:
print("hello")
输出:
hello
🌟 4️⃣ 小结对比表
写法 | 普通 Python 输出 | Jupyter 输出(直接写表达式) |
---|---|---|
print("hello") |
hello |
hello |
print('"hello"') |
"hello" |
"hello" |
print("'hello'") |
'hello' |
'hello' |
print(repr("hello")) |
'hello' |
'hello' |
"hello" (直接写表达式) |
(无输出) | 'hello' |
"he'llo" (直接写表达式) |
(无输出) | "he'llo" |
🌟 5️⃣ 小工具:自定义函数输出带引号的字符串
如果你希望每次都带引号打印,可以写一个小函数:
def show_with_quotes(s):
print(repr(s))
用法:
show_with_quotes("hello")
show_with_quotes("he'llo")
输出:
'hello'
"he'llo"
📝 复习重点
✅ print()
默认不输出字符串引号。
✅ 如果希望输出引号,可以:
- 在字符串中手写引号
- 用
repr()
✅ 在 Jupyter Notebook,直接写字符串表达式会显示带引号的 repr()
结果。