Here is an example:

def __str__(self):
    return f'({self.self.country},{self.self.code},{self.self.product}, {self.cost},{self.quantity })'

This way, when you assign values to a class, you can print its string representation

print(new_shoe)

More info here https://www.pythontutorial.net/python-oop/python-str/

Answer from ssanga on Stack Overflow
🌐
Python
docs.python.org › 3 › builtins › stdtypes.html
Built-in Types — Python 3.14.8 documentation
Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers.
🌐
W3Schools
w3schools.com › python › ref_func_str.asp
Python str() Function
The str() function converts the specified value into a string. ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
Discussions

In what cases do you use the str() function?
str() is used to generate a 'human readable string expression' for an object in python. Say for example , we have the following class in python: class Person: def __init__(self,name,age): self.name = name self.age = age print(Person('Anon',30)) This prints <__main__.Person object at 0x7f12b3fc7400> Which is a pointer to the memory address , not very helpful to comprehend. On the other hand , class Person: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return f"Name:{name} Age:{age}" print(Person('Anon',30)) will print Name:Anon Age:30 which is more human readable ( kinda). The same thing happens with int - it has an inbuilt __str__ method which parses the input and converts it into a human readable string ( using ASCII/UTF-8 conversion or whatever). If you are still interested , I'd recommend going and reading up on __repr__ , which is similar to __str__ but is intended to be used via debugging rather than returning a string representation. Tbf , you can get around this using fstrings .... More on reddit.com
🌐 r/learnpython
8
8
July 16, 2021
What does __str__ method do?
Yeah, it's just so you can print it. If you try to print a variable that is not a string it won't know what to do, so when you make a __str__ method it's like saying "If I tell you to print this variable, this is how I want you to do that" More on reddit.com
🌐 r/learnpython
13
4
November 14, 2020
python - How to use __str__ function to return a string representation of a class - Stack Overflow
I have been tasked with creating an inventory manager in python, and one of the required is to define the following function within the class: __str__ - This function returns a string representatio... More on stackoverflow.com
🌐 stackoverflow.com
What Are The Differences Between __str__ and __repr__ In Class Methods?
Hello folks, I am currently studying Python and currently on the topic of classes and overloading. I have seen __str__ and __repr__ used interchangeably. What are the main differences and what are the pros/cons of using one over the other? There was a test class in the book and I interchanged ... More on discuss.python.org
🌐 discuss.python.org
15
0
January 25, 2024
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-string.html
Python Strings
Similarly, if the start index is greater or equal to the end index, the slice is just the empty string. >>> s = 'Python' >>> s[2:999] 'thon' >>> s[3:2] # zero chars ''
🌐
Reddit
reddit.com › r/learnpython › in what cases do you use the str() function?
r/learnpython on Reddit: In what cases do you use the str() function?
July 16, 2021 -

Title. I know you use it for integers, but in what context? Also, is it used for anything else?

🌐
Google
developers.google.com › google for education › python › python strings
Python Strings | Python Education | Google for Developers
Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-str-function
Python str() function - GeeksforGeeks
July 15, 2025 - The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
String of ASCII characters which are considered printable by Python.
🌐
Reddit
reddit.com › r/learnpython › what does __str__ method do?
r/learnpython on Reddit: What does __str__ method do?
November 14, 2020 -

I'm still a beginner in python and my English is not really good, so I may have a little bit of understanding the explanation given in my course.

So I have this code:

class Apple:
    def __init__ (self,color,flavor):
        self.color=color
        self.flavor=flavor
        
    def __str__(self):
        return "This apple is {} and its flavor is {}".format(self.name,self.flavor)
        
jonagold=Apple("red","sweet")
print(jonagold)

The only purpose I see in using the __str__ method, I don't have to write the method in the print () line. If I changed the __str__ method with:

def say(self):
    return "This apple is {} and its flavor is {}".format(self.name,self.flavor)

I would just need to type

print(jonagold.say())

And I would get the same answer. What are the other purpose of using __str__? In what situation would I need to use the __str__?

Thank you :)

🌐
Real Python
realpython.com › ref › builtin-types › str
str | Python’s Built-in Data Types – Real Python
The built-in str data type represents sequences of characters and is used to manipulate textual data. Python strings are immutable sequences, meaning once defined, they can’t be changed.
🌐
Codecademy
codecademy.com › docs › python › dunder methods › __str__()
Python | Dunder Methods | __str__() | Codecademy
April 24, 2025 - In Python, objects can be represented as strings to make them more meaningful and easier to read. The __str__() method is one of Python’s special methods, also known as dunder methods (double underscore methods).
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-str-repr-functions
How To Use the __str__() and __repr__() Methods in Python | DigitalOcean
Learn Python’s str() and repr() methods in depth. Explore examples, best practices, and real-world tips for clarity and debugging.
🌐
GeeksforGeeks
geeksforgeeks.org › python › str-vs-repr-in-python
str() vs repr() in Python - GeeksforGeeks
July 23, 2025 - In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave.
🌐
Python.org
discuss.python.org › python help
What Are The Differences Between __str__ and __repr__ In Class Methods? - Python Help - Discussions on Python.org
January 25, 2024 - Hello folks, I am currently studying Python and currently on the topic of classes and overloading. I have seen __str__ and __repr__ used interchangeably. What are the main differences and what are the pros/cons of using one over the other? There was a test class in the book and I interchanged ...
🌐
Educative
educative.io › answers › what-is-the-str-method-in-python
What is the __str__ method in Python?
The __str__ method in Python represents class objects as a string. It can be used as a debugging tool when the members of a class need to be checked.
Top answer
1 of 3
10

In Python strings are objects, so that values is the size of the object itself. So this size will always be bigger than the string size itself.

From stringobject.h:

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;

From here you can get some clues on how those bytes are used:

  • len(str)+1 bytes to store the string itself;
  • 8 bytes for the hash;
  • (...)
2 of 3
3

You can find some information about the implementation if python strings in a weblog article by Laurent Luce. Additionally you can browse the source.

The size of string objects depends on the OS and type of machine and some choices. On 64-bit FreeBSD, using unicode for string literals (from __future__ import unicode_literals):

In [1]: dir(str)
Out[1]: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
 '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', 
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', 
'_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 
'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 
'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 
'swapcase', 'title', 'translate', 'upper', 'zfill']

In [2]: import sys

In [3]: sys.getsizeof("")
Out[3]: 52

In [4]: sys.getsizeof("test")
Out[4]: 68

In [7]: sys.getsizeof("t")
Out[7]: 56

In [8]: sys.getsizeof("te")
Out[8]: 60

In [9]: sys.getsizeof("tes")
Out[9]: 64

Every character uses 4 bytes extra in this case.

🌐
YouTube
youtube.com › practical coding
How to use str function in Python | Python functions made easy - YouTube
In this beginner's Python tutorial, you will learn how to convert an integer to a string in Python. To do so, you will learn how to use the str() function th...
Published: July 10, 2020
Views: 11K
🌐
Programiz
programiz.com › python-programming › methods › built-in › str
Python str() (With Examples)
Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... The str() method returns the string representation of a given object.
🌐
Codecademy
codecademy.com › learn › learn-python-3 › modules › learn-python3-strings › cheatsheet
Learn Python 3: Strings Cheatsheet | Codecademy
In computer science, sequences of characters are referred to as strings. Strings can be any length and can include any character such as letters, numbers, symbols, and whitespace (spaces, tabs, new lines).