Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Escape Characters

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Escape Characters

Python Escape Characters

In Python, escape characters help us include special symbols or behaviors in a string that wouldn’t normally be allowed. They always start with a backslash (\) followed by another character.

Let’s understand some of the most useful escape sequences with examples.

Inserting Quotes Inside Strings

Normally, using quotes inside a string with the same type of quotes will break your code. Escape characters fix that.

				
					quote1 = "She said, \"Let's learn Python!\""
quote2 = 'She said, \'Let\'s learn Python!\''

print(quote1)
print(quote2)

				
			

Output:

				
					She said, "Let's learn Python!"
She said, 'Let's learn Python!'


				
			

New Line (\n)

To break your string into multiple lines, use \n.

				
					message = "Dear Student,\nPlease submit your assignment by Monday."
print(message)


				
			

Output:

				
					Dear Student,
Please submit your assignment by Monday.


				
			

Tab (\t)

The \t escape adds a horizontal tab — useful for spacing.

				
					header = "Name\t\tScore\tGrade"
data = "Ali\t\t92\tA"
print(header)
print(data)

				
			

Output:

				
					Name		Score	Grade
Ali	    	92	    A


				
			

Backspace (\b)

The \b removes the character just before it. It’s like pressing backspace on your keyboard.

				
					text = "Your PIN is 1234\b5"
print(text)

				
			

Output:

				
					Your PIN is 1235

				
			

Here, \b removed 4, and 5 took its place.

Backslash (\\)

To include a backslash (\) in your string, escape it with another backslash.

				
					path = "C:\\Users\\Arshyan\\Documents"
print(path)

				
			

Output:

				
					C:\Users\Arshyan\Documents

				
			

Summary

Escape characters allow you to:

  • Insert quotes without breaking strings.

  • Add line breaks or tabs.

  • Simulate actions like backspace.

  • Display special characters like backslash.

They’re small but powerful tools for writing clean, readable, and flexible strings in Python.

Scroll to Top