How To Use Python String-Literal Modifiers
Learn this simple technique for modifying the behavior of Python strings
Python is so simple yet flexible — I love it. The language is easy to read, and I find myself doing minimal googling on syntax and conventions.
Python string-literal modifiers are letters directly in front of a string. For the uninitiated, they look like typos. What they actually do is change the behavior of that string—depending on the letter(s) used.
Let’s introduce each modifier and demonstrate the resulting modification.
Unicode String Modifier
This string modifier only applies to Python 2.x. Using the letter u at the beginning of the string converts it to Unicode, unlocking a wider character set at the expense of taking more memory.sys.getsizeof("hello world") # 48
sys.getsizeof(u"hello world") # 96
For Python 3.x, strings are Unicode by default, so this modifier would do nothing.
Byte String Modifier
This string modifier is the opposite of the Unicode string modifier. By placing the letter b at the beginning of a string, it’ll be converted to ASCII. At the expense of a smaller character set, this string will take less memory.sys.getsizeof("hello world") # 96
sys.getsizeof(b"hello world") # 48
If you didn’t get it yet, the byte string modifier only applies to Python 3.x — as Python 2.x strings are in ASCII by default.
Raw String Modifier
Use the letter r before a string to express that string—character for character—as is. What that means is escaped characters won’t be expressed as their special character but rather as plain text.print("hello\nworld")
"""
hello
world
"""print(r"hello\nworld")
"""
hello\nworld
"""
Format String Modifier
The format-string modifier was introduced in Python 3.6 and allows you to express variables within a string.name = "Jonathan"
print(f"Hello {name}") # Hello Jonathan
There are multiple ways to print a variable in a string, but f-strings have become my go-to method. Just make sure you’re running your code on 3.6+, or else you’ll receive a syntax error.