Python Programming

String Representations in Python — Understand repr() vs. str()

Know their usages and relationships

Yong Cui
The Startup
Published in
7 min readJun 6, 2020

--

Photo by Peter Lewicki on Unsplash

In a previous post, I talked about f-strings in Python. Briefly, f-strings are known as formatted string literals, which allow us to write more concise code to format strings in the way we want. Let’s take a quick refresh on the f-strings. In the code below, we declare a string variable name, and we call the print() function to log a message on the console.

# The basic use of f-string
>>> name = "Python"
>>> print(f"Hello, {name}!")
Hello, Python!

As you can see, we set an f-string as the argument for the print() function. In essence, we use the letter f (the uppercase F works too) preceding a regular string to denote the creation of an f-string. Within the string, we include the variable in a pair of curly braces such that the variable is interpolated. More broadly, the variable doesn’t have to be a str type, and it can be int, float, list, dict, set, and any type.

Moreover, we can do more with the interpolation of the variable by providing additional formatting options. One possible formatting option is to show the conversion of the variable by using !r or !s, which will display the string representation of the object by calling the repr() or…

--

--

Yong Cui
The Startup

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).