bhylu.com

Advertisements

Escape Characters

Escape sequences represent characters that are awkward to write literally in a string, such as a newline, tab, or the same quote that ends the string.

Understand the idea

A backslash introduces many escapes. Raw string literals keep most backslashes literal, which helps with regular-expression patterns, but they still obey Python's quoting rules. Use pathlib for file paths where possible rather than assembling Windows path separators by hand. The printed representation and the text itself can look different.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

message = "First line\nSecond line"
print(message)
print(repr(message))

Read the result

print displays two lines. repr displays a quoted representation containing the visible backslash-n escape so you can inspect where the newline lives.

Try one change

Compare a tab character with the two characters backslash and t. Use repr to make the difference visible.