Mark Redd

7 - Escape Characters

Based on the previous section, you may ask “What do I do if I need a string to have a mixture of double and single quotes?” For example:

John's character says, "I'd like to buy some cheese."

This is where escape characters come in handy. An escape character is a text character that can be represented by a backslash (\) followed by a character or series of characters (e.g. \t, \n, \u03b7). Escape characters make possible the mixing of single and double quotes (among many other things) as you will see in this next exercise.

Now go back to your text editor and write the following code (again, do NOT copy-paste it). Notice the use of escape characters and try to figure out what each one does.

# esc_chars.py

# here is an example of the use of escape characters
# Both of lines do the same thing
# Why might you prefer one over the other?
print("John's character says, \"I'd like to buy some cheese.\"")
print('John\'s character says, "I\'d like to buy some cheese."')

# here are some more escape character examples
# notice what all the other escape characters do
print("\nThere once was an old man from Peru")
print("who dreamed he was eating his shoe.")
print("\tHe woke up in fright,")
print("\tin the middle of the night,")
print("and found it was perfectly true!\n\n")

# here are a few more new characters and examples
print("\t\tI have tabbed over here!")

print("I am about to do a carriage return!\rI did it!--")

print("How do you print a backslash? \\ like that!")

print("\nI just made a new line! Now I will do another!\n")
print("Here is a greek eta character: \u03b7")

Here is what should happen

(If needed, see Section 4 to review how to run a script.)

$ python esc_chars.py
John's character says, "I'd like to buy some cheese."
John's character says, "I'd like to buy some cheese."

There once was an old man from Peru
who dreamed he was eating his shoe.
	He woke up in fright,
	in the middle of the night,
and found it was perfectly true!


		I have tabbed over here!
I did it!--to do a carriage return!
How do you print a backslash? \ like that!

I just made a new line! Now I will do another!

Here is a greek eta character: η

If on any of these exercises you do not see the output appear exactly as you saw it in the book, go back and fix it until it does.

What is happening here?

Let’s examine all the escape characters introduced in this exercise:

These are not all the potential escape characters. You can learn more about these by doing the exercises under Hone your skills. For now, understand that these are only a small part of python’s printing and display capabilities but what we have covered here are the most useful and used most often in programming.

Hone Your Skills

Advanced Mastery