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.
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()
Arguments | object | Object 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 Value | string | Returns 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'
Check out my 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).
Publisher 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.
Value | Meaning |
---|---|
'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!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.