Monday 20 September 2021

Python: How to place single quotes in a string

There are two solutions to this problem.

 

Solution 1: Keep the string in double quotes and use single quote as it is.

 

Example

str1 = "Hi, it's hari's book"

 

Solution 2: If you enclose the string in single quotes, use the escape (\) character to escape single quotes.

 

Example

 

str2 = 'Hi, it\'s hari\'s book'

 

escape_single_quote.py

str1 = "Hi, it's hari's book"
str2 = 'Hi, it\'s hari\'s book'

print('str1', ' -> ' , str1)
print('str2', ' -> ' , str2)

 

Output

str1  ->  Hi, it's hari's book
str2  ->  Hi, it's hari's book

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment