String And Literal In Python 3

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.

In [1]:
string = "I am John"
In [2]:
type(string)
Out[2]:
str

For literals, we have to use the single quotes.

In [3]:
literal = 'I am John'
In [4]:
type(literal)
Out[4]:
str

As we see both are string types.

In [5]:
literal==string
Out[5]:
True

Unicode literals in Python3

In Python3+, string,literals and unicode literals are same.

In [6]:
u'I am John' == 'I am John' == "I am John"
Out[6]:
True

We can also verify that by looking at the size of each data type.

In [7]:
import sys
In [8]:
sys.getsizeof(u'I am John')
Out[8]:
58
In [9]:
sys.getsizeof('I am John')
Out[9]:
58
In [10]:
sys.getsizeof("I am John")
Out[10]:
58

Double quotes inside Single quotes

Double quotes can be used inside single quotes without any problem.

In [11]:
literal = 'i am "Jonn"'
In [12]:
print(literal)
i am "Jonn"

Unbalanced double quotes inside Single Quotes

In [13]:
literal = 'i am "Jonn'
In [14]:
print(literal)
i am "Jonn

Backslashes inside Single Quotes

Backslashes inside literals are used to escape special characters. Let us look at following example.

In [15]:
literal = 'I am \John'
In [16]:
print(literal)
I am \John

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.

In [17]:
literal = 'I am John\'
  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.

In [20]:
literal = 'I am John\\'
In [21]:
print(literal)
I am John\

Below is an example in which we are using \n which is a built in special character in Python that means new line.

In [22]:
literal = 'I am \n John'
In [23]:
print(literal)
I am 
 John

Python r String

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.

In [24]:
literal = r'I am \n John'
In [25]:
print(literal)
I am \n John

Single quotes inside Double Quotes

In [26]:
string = "I am 'John'"
In [27]:
string
Out[27]:
"I am 'John'"

Unbalanced Single Quotes inside Double Quotes

In [28]:
string = "I am 'John"
In [29]:
string
Out[29]:
"I am 'John"