简体   繁体   中英

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. thank u very much:)

image

This behaviour is normal. In the first example, you are using a Python feature called argument unpacking. The print function uses *args to mean it takes any number of arguments. However, your totalMessage is a tuple, meaning you are only passing a tuple to the printing 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. totalMessage , however, is not a new string, but a tuple of strings. When Python prints a tuple, it prints the actual contents of the elements of the tuple (which in general may not be strings).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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