In our introduction to strings, we learned that we can use either single quotes or double quotes to create / declare a string.
Well, sometimes you'll have to choose between these two to not run into issues. Those situations are when our text contains quotation marks.
For example, suppose we want to print the string My name's Andy. If we surrond the text by single quotes:
print('My name's Andy')
This code would produce a SyntaxError
You can also see by the text color that we have a problem. Python reads the first apostrophe and interprets that a string declaration starts there. Then it starts parsing through characters until it finds the second apostrophe and interprets that the string declaration ends there.
So it concludes that the string is 'My name' but then it cannot understand the code coming after that: s Andy').
We can solve this by using double quotes to wrap up the text:
print("My name's Andy")
The output of this code is:
My name's Andy
A string declaration starting with a " can be ended only by another ". And so the interpreter will not stop when reaching the ' and will successfully read the whole string.
The same thing happens if we want to have double quotes as part of the string's content:
Surrounding by double quotes doesn't work:
print("Hey "bro"") # SyntaxError
Surrounding by single quotes works:
print('Hey "bro"') # Output: Hey "bro"
Assignment
Follow the Coding Tutorial and let's practice with quotes!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
