Python str() Function

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.

Python str() Function Built-in -- Explanation

Syntax str()

Syntax: 
str(object)   
# --> Most common case: convert an object to a string

str(object=b'', encoding='utf-8', errors='strict')   
# --> Not so common case: Converts a bytes or bytearray to a string by calling the method bytes.decode()
ArgumentsobjectObject to be converted to a string. If empty or not provided, returns the empty string ''.
encoding(Optional) Only if object is a bytes object. The encoding used—for example ASCII or UTF-8.
errors(Optional) One of the options: 'strict', 'replace', or 'ignore'. See table below for more details.
Return ValuestringReturns a string value as defined by the object.__str__() method.

Video str()

Usage Examples str()

The following code shows you how to use the str(x) function on how to convert an object to a string:

>>> str(42)
'42'
>>> str(3.14)
'3.14'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> str({'Donna': 33, 'Harvey': 44})
"{'Donna': 33, 'Harvey': 44}"

The following code shows you how to use bytes or bytearray inputs as object argument.

>>> str(b'hello')
"b'hello'"
>>> str(b'hello', encoding='UTF-8')
'hello'
>>> str(b'hello', encoding='UTF-8', errors='ignore')
'hello'

But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners

How to Implement Your Own String Representation for a Custom Object

To implement your own string representation when using the str(object) function on your custom object, overwrite the object.__str__() method when defining the class and return the desired string representation of the given object. If no __str__() method is defined, Python uses the __repr__ method as a fallback that’s implemented per default for any object.

class Car:
    def __init__(self, color, brand):
        self.color = color
        self.brand = brand

    def __str__(self):
        return 'Your car has color ' + self.color + ' and brand ' + self.brand

    def __repr__(self):
        return '123'

    
porsche = Car('black', 'porsche')
tesla = Car('silver', 'tesla')

print(str(porsche))
print(str(tesla))

The output is:

Your car has color black and brand porsche
Your car has color silver and brand tesla

Note how the __str__ method takes precedence over the __repr__ method. But if you skip the definition of the __str__ method, it’ll take the string returned by the __repr__ method:

class Car:
    def __init__(self, color, brand):
        self.color = color
        self.brand = brand

    def __repr__(self):
        return '123'

    
porsche = Car('black', 'porsche')
tesla = Car('silver', 'tesla')

print(str(porsche))
print(str(tesla))

The output now is:

123
123

[Table] 7 Different “errors” Arguments of str()

You can use the following error handlers in the str() function when using a bytes or bytearray input argument.

ValueMeaning
'strict'(Default) Raise UnicodeError
'ignore'If data input would cause an error, ignore it and continue without notice.
'replace'Replace with replacement marker U+FFFD for decoding codecs, and '?' on encoding.
'xmlcharrefreplace'Replace with XML character reference for encoding.
'backslashreplace'Replace with escape sequences.
'namereplace'Replace with \N{...} escape sequences for encoding.
'surrogateescape'Replace byte with individual surrogate code ranging from U+DC80 to U+DCFF.

You can find more details about these error handlers at the source here.

Summary

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!