16 Python String Things I Regret Not Knowing Earlier
When programming in Python, we will most likely deal with strings one way or another.
Here are 16 Python string things I regret not knowing earlier after 8 years of learning Python.
1) Formatted strings (f-strings)
To create a formatted string (thereinafter known as f-strings), we simply need to add an f in front of our string’s quotes:
Also, we can use the { } curly braces to insert variables inside an f-string — like name and age in the example above.
In addition, f-strings provide us with some useful additional functionality — for instance, if we add = after a variable, we print both the variable name and value:
If we add .3f after a number, we automatically round that number to 3 decimal places:
F-strings provide us with many many other functionalities, but I won’t run through them exhaustively here as I have many other Python string quirks to share first.
2) The ‘string’ module
Have you ever needed all the alphabets and manually typed out:
I’m here to inform you that the built-in string module can help us with this:
No need to type out all the alphabets anymore (NGL typing out all alphabets gets annoying after a while)
The string module also provides us with other useful string functionality eg. printing alphabets in lowercase, uppercase or both cases, or even printing all punctuations.
3) The .join() method
I learnt about the .join() method a little late. And before I knew of this method, I used to do whacky stuff to connect a list of strings with some character:
We can achieve this in one line using the .join() method, which in the case below, puts a ‘-’ character between all strings in the list.
4) Unicode characters
Using unicode, we can print special characters in normal Python strings:
To print a unicode character, we need to:
google its unicode code — eg. ‘03A9’ for the Ohm character
Add a ‘\u’ in front of the code — eg. \u03A9
Add this to a string and print it
Note — a unicode character is treated as a single character
We can print many special characters in our strings using unicode:
Quick pause
If you wish to support me as a writer, do also consider buying my book — 101 Things I Never Knew About Python: https://payhip.com/b/vywcf
5) The .format() method
The .format() method of a string allows us to insert variables into a template string.
We can reuse this template string repeatedly for different variables, and can even store this template string in our database and such.
6) Single quotes VS double quotes
When creating strings, both single or double quotes work just fine:
If we want to insert ‘ characters, we need to escape it using \ if we use single quotes. Conversely, we don’t need to if we use double quotes:
Similarly, if we want to insert “ characters, we need to escape them using \ if we use double quotes. Conversely, we don’t need to if we use single quotes:
Personally, I find myself inserting more ‘ characters than “ characters as ‘ is a apostrophe mark. So I usually use double quotes in these cases.
7) Triple quoted strings
We can use triple quotes to create strings that span over multiple lines:
Here, notice that the newline characters inside the triple quoted string are actually registered as newline characters.
Note — we can use either single or double quotes to make triple quoted strings:
I use triple quoted strings most when writing docstrings for my functions:
8) The __str__ magic method
When we initialize custom objects and print them, we get some gibberish like <__main__.Dog object at some_gibberish>.
^ This is the behaviour of the default __str__ method. When we print(dog), we automatically call str(dog), which returns the above gibberish string.
If we override the __str__ magic method in our class definition, we can control what happens when we call str(dog):
Note — the __str__ magic method must return a string. Or else we get an error.
The __str__ magic method is thus useful if we want to create a human-readable representation of our custom object.
9) __str__ VS __repr__
Similar to the __str__ method, the __repr__ method is meant to return a string representation of our custom object.
Like how the str() function calls the __str__ magic method, the repr() function calls the __repr__ magic method.
The difference in __str__ and __repr__ lies in the intent:
the __str__ method intends to return a human-readable representation of the object
the __repr__ method intends to return a computer-readable representation of the object for debugging purposes.
One obvious example is the built-in datetime object:
Notice that str(dt) returns a string we humans are familiar with, but repr(dt) returns a string that we can easily copy paste to recreate the datetime object.
Keep reading with a 7-day free trial
Subscribe to The Python Rabbithole to keep reading this post and get 7 days of free access to the full post archives.