Home > Blockchain >  functioning of \n in python3
functioning of \n in python3

Time:01-22

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

CodePudding user response:

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.

CodePudding user response:

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).

CodePudding user response:

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 )

For future reference, please put your code within the body of the post itself, rather than including an image. This makes it easier to view and copy/paste.

  •  Tags:  
  • Related