Skip to content
Home » Strings with Escape Sequences in Python

Strings with Escape Sequences in Python

Spread the love

Today we’ll be talking about escape sequences.

Escape characters / sequences are characters used to escape the special meaning of another character.

escape sequences

We use the backslash (\) character to escape characters.

Escape sequences:

\nnew line

This sequence is used for a new line:

>>> a = "Let's break the line \nright here"
>>> print(a)
Let's break the line 
right here

Escape characters don’t work if we echo strings:

>>> a
"Let's break the line \nright here"
\thorizontal tab

This sequence adds tabs:

>>> a = "We need more \t\t\t\t\t\t\t tabs!"
>>> print(a)
We need more 							 tabs!
\\backslash

This sequence should be used if you need a single backslash.

>>> a = "I need a single \\ here."
>>> print(a)
I need a single \ here.

If you need a double one, just add one more:

>>> a = "I need a double \\\ here."
>>> print(a)
I need a double \\ here.
\’single quote

This sequence is used for a single quote:

>>> a = '"How about a single \'?", he asked.'
>>> print(a)
"How about a single '?", he asked.
\”double quote

And this sequence is used for a double quote:

>>> a = "Double \" seems right."
>>> print(a)
Double " seems right.
\uxxxxUnicode character with 16-bit hex value xxxx

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

This sequence can be used for Unicode characters.

>>> a = "The first letter is \u0041."
>>> print(a)
The first letter is A.

This is particularly useful for characters from other alphabets. You can find the Unicode code points online. For example let’s take this code point: U+19EC:

>>> a = "What does \u19ec mean?"
>>> print(a)
What does ᧬ mean?

or this one: U+231A for the symbol of a watch:

>>> a = "Watch your \u231a!"
>>> print(a)
Watch your ⌚!

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love
Tags:

Leave a Reply