Escape Characters
Sometimes you need to put “illegal” characters inside a string. For example, if you use single quotes for a string, but the text itself contains a contraction like 'don't, ...' Python will get confused.
We use the backslash (\) to “escape” these characters, telling Python: “Treat the next character as plain text, not code.”
# Without the backslash, this would throw a SyntaxError
message = 'She said, "It\'s a beautiful day!"'
# \n inserts a newline (like hitting Enter)
print("Line one\nLine two")
# \\ displays an actual backslash
print("C:\\Users\\Daniel")
If you have a lot of backslashes (like in a Windows file path), you can put an r before the quotes to create a Raw String. This tells Python to ignore all escape characters.
# The \n won't create a newline here
path = r"C:\Users\Daniel\new_folder"
Advanced F-Strings
F-strings allow you to run math or call functions directly inside the curly braces {}.
# Quick math inside a string
print(f"10 times 5 is {10 * 5}")
name = "DANIEL"
print(f"Lowercased: {name.lower()}")
Numeric Formatting
When dealing with data, you often get “ugly” numbers with way too many decimals (e.g., 0.87654321). F-strings have a built-in way to clean these up using a colon : followed by a format specifier.
Rounding Decimals
Use :.2f to round a number to two decimal places (the f stands for “fixed-point”).
pi = 3.14159265
print(f"Pi rounded: {pi:.2f}") # Output: 3.14
Adding Commas
For large numbers, use :, to add thousands separators automatically.
salary = 125000
print(f"Your salary is ${salary:,}") # Output: $125,000
Alignment and Padding
You can force strings to take up a specific amount of space. This is great for making clean logs or tables in your console.
<: Left align (default for strings)>: Right align (default for numbers)^: Center align
name = "Daniel"
print(f"|{name:<10}|") # |Daniel |
print(f"|{name:>10}|") # | Daniel|
print(f"|{name:^10}|") # | Daniel |
You can even specify a character to fill the empty space:
print(f"{name:=^20}")
# Output: =======Daniel=======
In older code (prior to Python 3.6), you may see .format() method or the even older % operator. However, F-strings are faster and easier to read.