2.1.1.11 Your very first program

The print() function - the escape and newline characters

We've modified the code again. Look at it carefully.
There are two very subtle changes - we've inserted a strange pair of characters inside the rhyme. They look like this: \n.

Interestingly, while you can see two characters, Python sees one.
The backslash (\) has a very special meaning when used inside strings - this is called the escape character.
The word escape should be understood specifically - it means that the series of characters in the string escapes for the moment (a very short moment) to introduce a special inclusion.
In other words, the backslash doesn't mean anything in itself, but is only a kind of announcement, that the next character after the backslash has a different meaning too.
The letter n placed after the backslash comes from the word newline.
Both the backslash and the n form a special symbol named a newline character, which urges the console to start a new output line.
Run the code. Your console should now look like this:
The itsy bitsy spider climbed up the waterspout. Down came the rain and washed the spider out.
output
As you can see, two newlines appear in the nursery rhyme, in the places where the \n have been used.

print("The itsy bitsy spider\nclimbed up the waterspout.")
print()
print("Down came the rain\nand washed the spider out.")
  • Console 

Comments

Popular Posts