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"
For literals, we have to use the single quotes.
literal = 'I am John'
As we see both are string types.
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.
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"'
i am "Jonn"
literal = 'i am "Jonn'
i am "Jonn
Backslashes inside literals are used to escape special characters. Let us look at following example.
literal = 'I am \John'
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.
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.
literal = 'I am John\\'
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.
literal = 'I am \n John'
I am John
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'
I am \n John
string = "I am 'John'"
"I am 'John'"
string = "I am 'John"
"I am 'John"
- Strftime and Strptime In Python
- How To Code RNN and LSTM Neural Networks in Python
- SVM Sklearn In Python
- Summarising Aggregating and Grouping data in Python Pandas
- Python Pandas String To Integer And Integer To String DataFrame
- Merge and Join DataFrames with Pandas in Python
- Five Ways To Remove Characters From A String In Python
- Append In Python
- Select Pandas Dataframe Rows And Columns Using iloc loc and ix