简体   繁体   English

\n 在 python3 中的功能

[英]functioning of \n in python3

i'm new in programming so maybe this question is a easy one for you all:) So as you can see in the code, when i print the messages it prints each message with the correct function of \n, but when i take all the messages and create a new one that has all of them called "totalMessages" when i print it it takes the \n like it was part of the text, so i really want to understand why is this is happening and i hope i that have explained everything in a understandable way.我是编程新手,所以也许这个问题对你们所有人来说都是一个简单的问题:) 所以正如您在代码中看到的那样,当我打印消息时,它会使用 \n 的正确 function 打印每条消息,但是当我把所有消息并创建一个新消息,当我打印它时,所有消息都称为“totalMessages”,它需要 \n 就像它是文本的一部分,所以我真的很想了解为什么会发生这种情况,我希望我有以通俗易懂的方式解释了一切。 thank u very much:)非常感谢:)

image图片

This behaviour is normal.这种行为是正常的。 In the first example, you are using a Python feature called argument unpacking.在第一个示例中,您正在使用称为参数解包的 Python 功能。 The print function uses *args to mean it takes any number of arguments.打印 function 使用 *args 表示它需要任意数量的 arguments。 However, your totalMessage is a tuple, meaning you are only passing a tuple to the printing function.但是,您的totalMessage是一个元组,这意味着您只是将一个元组传递给打印 function。

Also, please show the code in your question rather than in images.另外,请在您的问题中而不是图像中显示代码。 It is much easier to read and understand.它更容易阅读和理解。 You can use code blocks or ` characters for this.您可以为此使用代码块或 ` 字符。

When Python prints a string, it interprets \n as a newline.当 Python 打印字符串时,它会将\n解释为换行符。 totalMessage , however, is not a new string, but a tuple of strings.然而, totalMessage不是一个新字符串,而是一个字符串元组。 When Python prints a tuple, it prints the actual contents of the elements of the tuple (which in general may not be strings).当 Python 打印元组时,它会打印元组元素的实际内容(通常可能不是字符串)。

You need to concatenate your strings together to combine them into one string.您需要将字符串连接在一起以将它们组合成一个字符串。 This is done by putting a '+' between them.这是通过在它们之间放置一个“+”来完成的。 Using '(' and ')' is creating a tuple instead.使用 '(' 和 ')' 正在创建一个元组。 Try this:尝试这个:

gamers = ["Toyota", "fiat", "ford", "susuki", "chevro"]
message1 = f"\nprima macchina {gamers[0].title()}"
message2 = f"\n\nMacchina italia {gamers[1].title()}"
...
totalMessage = message1 + message2 + ...

print( message1, message2, ... )
print( totalMessage )

Also, in the future I recommend putting your code within the body of the post itself (by indenting it with four spaces), rather than including an image.此外,将来我建议将您的代码放在帖子本身的正文中(通过缩进四个空格),而不是包含图像。 This makes it easier to view and copy/paste.这使得查看和复制/粘贴变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM