\n 在 python 中的工作 [英] working of \n in python

查看:78
本文介绍了\n 在 python 中的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Python 课程.在谈论转义序列时,他们提到 "\n" 用于在新行中打印字符串.但是当它以下列方式使用时为什么我得到不同的输出

<预><代码>>>>st = "你好\n世界">>>英石'你好\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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆