In this notebook, I will talk about basics of string and Literal in Python. Following notebook has been built using Python3.6
Let us start with Python string. String can be declared in Python using double quotes.
For literals, we have to use the single quotes.
As we see both are string types.
In Python3+, string,literals and unicode literals are same.
We can also verify that by looking at the size of each data type.
Double quotes can be used inside single quotes without any problem.
Backslashes inside literals are used to escape special characters. Let us look at following example.
In the above example, backslash J is printed as it is because J is not special character.
To see the difference, let use put the backslash before the closing single quote and see what happens.
File “<ipython-input-17-5dd7ec96cdb2>”, line 1
literal = ‘I am John’
SyntaxError: EOL while scanning string literal
You see, we got an error because ‘ escapes the single quote and that means our literal string has no closing quote now. To make it work and tell Python that ignore backslash and treat it as a normal character, we need to add one more backslash.
Below is an example in which we are using n which is a built in special character in Python that means new line.
If you don’t want the above default behavior and let Python treat n as normal character, use r in front of the single quotes. r stands for raw string in Python.