\n 在 python 中的工作 [英] working of \n in python
问题描述
我目前正在学习 Python 课程.在谈论转义序列时,他们提到 "\n"
用于在新行中打印字符串.但是当它以下列方式使用时为什么我得到不同的输出
但是如果我这样做
<预><代码>>>>打印你好世界有两个函数可以给出对象的字符串表示,repr()
和 str()
.前者旨在将对象转换为 as-code 字符串,而后者提供用户友好的字符串.
在命令行输入变量名时,使用repr()
,\n
字符显示为\n
(作为代码).当您使用 print
时,使用 str()
,并且 \n
显示为新行(用户友好).
顺便说一下,str
是一个不好的变量名,因为它与内置变量相同.
I am currently taking a course in python. When talking about escape sequences they told about "\n"
is used for printing strings in new line. But when it is used in the following ways why I am getting a different output
>>> st = "Hello\nWorld"
>>> st
'Hello\nWorld'
But if I do
>>> print st
Hello
World
There are two functions that give an object's string representation, repr()
and str()
. The former is designed to convert the object to as-code string, while the latter gives user-friendly string.
When you input the variable name in the command line, repr()
is used, and \n
character is shown as \n
(as-code). When you use print
, str()
is used, and \n
is shown as a new line (user-friendly).
By the way, str
is a bad name for a variable, as it's the same as the built-in.
这篇关于\n 在 python 中的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!