Saturday, November 23, 2024
Google search engine
HomeLanguagesSingle and Double Quotes | Python

Single and Double Quotes | Python

Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement. Sometimes we have to use quotes (single or double quotes) together in the same string, in such cases, we use single and double quotes alternatively so that they can be distinguished. 

Example #1: Check the below example and analyze the error –

#Gives Error
print('It's python')

Explanation – It gives an invalid syntax error. Because a single quote after “it” is considered the end of the string and rest part is not part of a string. It can be corrected as: 

Python3




print("It's Python !")


Output:

It's Python!

Example #2: If you want to print ‘WithQuotes’ in python, this can’t be done with only single (or double) quotes alone, it requires simultaneous use of both. 

 Approach:

  1. The first line of the program uses the print() function to print the string “‘WithQuotes’” enclosed within single quotes. The inner single quotes are escaped using a backslash to prevent them from ending the string prematurely.
  2. The second line of the program uses the print() function to print the string “Hello ‘Python’” which contains a single quote within double quotes. The single quote is not escaped since it is inside a string enclosed within double quotes.
  3. The third line of the program uses the print() function to print the string “”WithQuotes”” enclosed within double quotes. The inner double quotes are escaped using HTML entity codes to prevent them from ending the string prematurely.
  4. The fourth line of the program uses the print() function to print the string “Hello “Python”” which contains double quotes within single quotes. The double quotes are also escaped using HTML entity codes since they are inside a string enclosed within single quotes.

Python3




# this code prints the output within quotes.
# print WithQuotes within single quotes
print("'WithQuotes'")
print("Hello 'Python'")
 
# print WithQuotes within single quotes
print('"WithQuotes"')
print('Hello "Python"')


Output –

'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"

Time complexity: O(1) as the execution time does not depend on the input size. 
Auxiliary space: O(1) as the space used by the program is constant and does not depend on the input size.

Conclusion: The choice between both types (single quotes and double quotes) depends on the programmer’s choice. Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it’s sometimes our need to use one type over the other.

RELATED ARTICLES

Most Popular

Recent Comments