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.
string = "I am John"
type(string)
For literals, we have to use the single quotes.
literal = 'I am John'
type(literal)
As we see both are string types.
literal==string
In Python3+, string,literals and unicode literals are same.
u'I am John' == 'I am John' == "I am John"
We can also verify that by looking at the size of each data type.
import sys
sys.getsizeof(u'I am John')
sys.getsizeof('I am John')
sys.getsizeof("I am John")
Double quotes can be used inside single quotes without any problem.
literal = 'i am "Jonn"'
print(literal)
literal = 'i am "Jonn'
print(literal)
Backslashes inside literals are used to escape special characters. Let us look at following example.
literal = 'I am \John'
print(literal)
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.
literal = 'I am John\'
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.
literal = 'I am John\\'
print(literal)
Below is an example in which we are using \n which is a built in special character in Python that means new line.
literal = 'I am \n John'
print(literal)
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.
literal = r'I am \n John'
print(literal)
string = "I am 'John'"
string
string = "I am 'John"
string
Related Notebooks
- Strftime and Strptime In Python
- Summarising Aggregating and Grouping data in Python Pandas
- Merge and Join DataFrames with Pandas in Python
- Write Single And Multi Line Comments In Python
- PySpark Substr and Substring
- Python Pandas String To Integer And Integer To String DataFrame
- Python Iterators And Generators
- Python Sort And Sorted
- How To Code RNN and LSTM Neural Networks in Python