Escape single quote in a String
To escape single quote character in a string in Python, when the string is created using single quotes, place a backslash character before the single quote character inside the string.
In the following example, User's World
is string value. We escape the single quote character inside the string, as shown in the following.
'User\'s World'
Program
In the following program, we create a string message
, with single quote character escaped using backslash character, and print this string to console output.
main.py
message = 'User\'s World'
print(message)
Output
User's World
If the string is defined using double quotes, then there is no need to escape a single quote. The single quote in this scenario is a valid character.
main.py
message = "User's World"
print(message)
Output
User's World
Conclusion
In this Python Tutorial, we learned how to escape a single quote character inside a string, using backslash character.