Difficulty: Beginner
Strings in Python are sequences of characters enclosed in quotes. You can use single quotes ('hello'), double quotes ("hello"), or triple quotes ('''hello''' or """hello""") to create strings. Single and double quotes work identically for single-line strings, so choose whichever avoids the need for escaping internal quotes.
Triple-quoted strings can span multiple lines and preserve line breaks. They are commonly used for docstrings (documentation strings inside functions, classes, and modules) and for any text that naturally spans several lines.
Escape characters let you include special characters inside strings. The backslash (\) is the escape character: \n inserts a newline, \t inserts a tab, \\ inserts a literal backslash, and \' or \" inserts a quote character. These are essential when you need characters that cannot be typed directly into a string literal.
Raw strings, prefixed with r or R, treat backslashes as literal characters instead of escape characters. Writing r"C:\Users\name" keeps every backslash as-is, which is especially useful for Windows file paths and regular expressions where backslashes appear frequently.
single = 'Hello, World!'
double = "Hello, World!"
triple = '''This is
a multi-line
string.'''
print(single)
print(double)
print(triple)
Single and double quotes produce identical strings. Triple quotes preserve newlines and allow the string to span multiple lines in source code.
tab_example = "Name:\tAlice"
newline_example = "Line 1\nLine 2"
quote_example = "She said \"hi\""
backslash_example = "C:\\Users\\Alice"
print(tab_example)
print(newline_example)
print(quote_example)
print(backslash_example)
\t produces a tab, \n produces a newline, \" inserts a double quote inside a double-quoted string, and \\ produces a single backslash.
normal = "C:\\new_folder\\test"
raw = r"C:\new_folder\test"
print(normal)
print(raw)
print(normal == raw)
The raw string r"..." treats backslashes literally, so \n is two characters (backslash + n) rather than a newline. Both variables produce the same string.
strings, quotes, escape characters, raw strings