{"id":1060,"date":"2023-04-13T22:00:00","date_gmt":"2023-04-13T16:30:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=1060"},"modified":"2023-08-15T13:33:35","modified_gmt":"2023-08-15T08:03:35","slug":"str-and-repr-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/str-and-repr-in-python","title":{"rendered":"__str__ &#038; __repr__: Change String Representation In Python"},"content":{"rendered":"\n<p>In the program output, we can represent Python strings in two ways. Python supports both informal and formal string representations. When we run the Python program to print the string, we get an informal representation of it in the output.<\/p>\n\n\n\n<p>The&nbsp;<code>__str__<\/code>&nbsp;method in Python is responsible for the informal representation of the object, which we can change to the formal representation by using the&nbsp;<code>__repr__<\/code>&nbsp;method.<\/p>\n\n\n\n<p>In this article, we&#8217;ll discuss these dunder methods named&nbsp;<code>__str__<\/code>&nbsp;and&nbsp;<code>__repr__<\/code>&nbsp;and how they are used for changing the representation of the string.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-str-and-repr-method\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-str-and-repr-method\"><\/a>__str__() and __repr__() method<\/h2>\n\n\n\n<p>The&nbsp;<code>__str__()<\/code>&nbsp;method returns the object&#8217;s easily-readable or informal string representation. Python calls the&nbsp;<code>__str__()<\/code>&nbsp;method internally when we call functions like&nbsp;<code>str()<\/code>&nbsp;and&nbsp;<code>print()<\/code>.<\/p>\n\n\n\n<p>The&nbsp;<code>__repr__()<\/code>&nbsp;method, unlike the&nbsp;<code>__str__()<\/code>&nbsp;method, returns a more informative or formal string representation of the object. When the&nbsp;<code>__str__()<\/code>&nbsp;method for the class is not defined, the object calls the&nbsp;<code>__repr__()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>Overall, the&nbsp;<code>__str__()<\/code>&nbsp;method is meant for users, whereas the&nbsp;<code>__repr__()<\/code>&nbsp;method is meant for developers and can be more useful when debugging.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-default-implementation\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-default-implementation\"><\/a>Default implementation<\/h3>\n\n\n\n<p>We can implement these methods within the Python class to see them in action. Let&#8217;s look at the following example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Python class is created\nclass Product:\n    def __init__(self, name, category):\n        self.name = name\n        self.category = category\n\n# Instantiated the class\ndata = Product('Ford', 'Car')\n\n# Implemented the __str__() method\nprint(data.__str__())\nprint(data.__repr__())\nprint(data)<\/pre><\/div>\n\n\n\n<p>We created the&nbsp;<code>Product<\/code>&nbsp;class and defined the&nbsp;<code>__init__<\/code>&nbsp;function that takes&nbsp;<code>name<\/code>&nbsp;and&nbsp;<code>category<\/code>. Then we instantiated the class&nbsp;<code>Product<\/code>&nbsp;with the necessary arguments.<\/p>\n\n\n\n<p>Then we implemented the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;methods to the object of the class&nbsp;<code>Product<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">&lt;__main__.Product object at 0x000002157F10C370&gt;\n&lt;__main__.Product object at 0x000002157F10C370&gt;\n&lt;__main__.Product object at 0x000002157F10C370&gt;<\/pre><\/div>\n\n\n\n<p>When we ran the above code, we got the object&#8217;s location in the processor&#8217;s memory as a hexadecimal number.<\/p>\n\n\n\n<p>This happened because we didn&#8217;t implement the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;methods within our class&nbsp;<code>Product<\/code>. Thus, calling the&nbsp;<code>__str__()<\/code>&nbsp;method calls the default&nbsp;<code>__repr__()<\/code>&nbsp;method and shows the same output.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-custom-str-method\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-custom-str-method\"><\/a>Custom __str__() method<\/h3>\n\n\n\n<p>In the following code, we implemented the custom&nbsp;<code>__str__()<\/code>&nbsp;method that returns a string with some information and then we executed the code to see what would be the output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Python class is created\nclass Product:\n    def __init__(self, name, category):\n        self.name = name\n        self.category = category\n\n    # Creating __str__() function\n    def __str__(self):\n        return f'The {self.name} belongs to category {self.category}.'\n\n# Instantiated the class\ndata = Product('Ford', 'Car')\n\n# Implemented the __str__() method\nprint(data.__str__())\nprint(data.__repr__())\nprint(data)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">The Ford belongs to category Car.\n&lt;__main__.Product object at 0x00000156D7E5C370&gt;\nThe Ford belongs to category Car.<\/pre><\/div>\n\n\n\n<p>We got the string defined in the class&#8217;s&nbsp;<code>__str__()<\/code>&nbsp;method when we called the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>print()<\/code>&nbsp;methods on the object&nbsp;<code>data<\/code>, but not when we called the&nbsp;<code>__repr__()<\/code>&nbsp;method on the object&nbsp;<code>data<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-only-repr-method\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-only-repr-method\"><\/a>Only __repr__() method<\/h3>\n\n\n\n<p><strong>What if we only implement the<\/strong>&nbsp;<code>__repr__()<\/code>&nbsp;<strong>method within the class<\/strong>&nbsp;<code>Product<\/code><strong>?<\/strong><\/p>\n\n\n\n<p>We&#8217;ve added the&nbsp;<code>__repr__()<\/code>&nbsp;method to the&nbsp;<code>Product<\/code>&nbsp;class, which returns a string containing the product name and category.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Python class is created\nclass Product:\n    def __init__(self, name, category):\n        self.name = name\n        self.category = category\n\n    # Creating __repr__() function\n    def __repr__(self):\n        return f'Product: {self.name} - Category: {self.category}.'\n\n# Instantiated the class\ndata = Product('Ford', 'Car')\n\n# Called the __str__() method\nprint(data.__str__())\n# Called the __repr__() method\nprint(data.__repr__())\nprint(data)\n# Called the str() function\nprint(str(data))<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Product: Ford - Category: Car.\nProduct: Ford - Category: Car.\nProduct: Ford - Category: Car.\nProduct: Ford - Category: Car.<\/pre><\/div>\n\n\n\n<p>As previously discussed, if&nbsp;<code>__str__()<\/code>&nbsp;is not defined for the class, the object will invoke the class&#8217;s&nbsp;<code>__repr__()<\/code>&nbsp;method. That&#8217;s why we got the string even though we called&nbsp;<code>__str__()<\/code>,&nbsp;<code>print()<\/code>, and&nbsp;<code>str()<\/code>&nbsp;on the object&nbsp;<code>data<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-calling-str-and-repr-on-built-in-class\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-calling-str-and-repr-on-built-in-class\"><\/a>Calling __str__() and __repr__() on built-in class<\/h2>\n\n\n\n<p>So far, we&#8217;ve used user-defined classes to implement the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;methods. Now we&#8217;ll look at how these methods are implemented in Python&#8217;s built-in classes.<\/p>\n\n\n\n<p>We&#8217;ll see what happens when we call the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;methods on the Python built-in&nbsp;<code>datetime<\/code>&nbsp;module&#8217;s classes.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import datetime\n\ntoday = datetime.datetime.today()\n\nprint(f'Normal: {today}')\nprint('-'*20)\nprint(f'__str__ method: {today.__str__()}')\nprint(f'str() method: {str(today)}')\nprint('-'*20)\nprint(f'__repr__ method: {today.__repr__()}')\nprint(f'repr() method: {repr(today)}')<\/pre><\/div>\n\n\n\n<p>We used the&nbsp;<code>__str__()<\/code>,&nbsp;<code>str()<\/code>,&nbsp;<code>__repr__()<\/code>, and&nbsp;<code>repr()<\/code>&nbsp;methods on the variable&nbsp;<code>today<\/code>&nbsp;to print the current date and time.<\/p>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Normal: 2023-04-12 18:16:27.991308\n--------------------\n__str__ method: 2023-04-12 18:16:27.991308\nstr() method: 2023-04-12 18:16:27.991308\n--------------------\n__repr__ method: datetime.datetime(2023, 4, 12, 18, 16, 27, 991308)\nrepr() method: datetime.datetime(2023, 4, 12, 18, 16, 27, 991308)<\/pre><\/div>\n\n\n\n<p>The output shows that the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>str()<\/code>&nbsp;methods returned an informal or easily readable string representation, whereas the&nbsp;<code>__repr__()<\/code>&nbsp;and&nbsp;<code>repr()<\/code>&nbsp;methods returned a more informative or formal string representation.<\/p>\n\n\n\n<p>The&nbsp;<code>__str__()<\/code>&nbsp;method is implemented by default in pre-defined or built-in Python classes, so we don&#8217;t need to define them explicitly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/str-and-repr-in-python#heading-conclusion\"><\/a>Conclusion<\/h2>\n\n\n\n<p>The methods&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;are used to represent objects in string format. The&nbsp;<code>__str__()<\/code>&nbsp;method returns a human-readable or informal string representation of the object, whereas the&nbsp;<code>__repr__()<\/code>&nbsp;method returns a more informative or formal string representation of the object.<\/p>\n\n\n\n<p>The&nbsp;<code>__str__()<\/code>&nbsp;method is for users, whereas the&nbsp;<code>__repr__()<\/code>&nbsp;method is for developers because it is more useful when debugging.<\/p>\n\n\n\n<p>For pre-defined or built-in Python classes, we don&#8217;t need to define the&nbsp;<code>__str__()<\/code>&nbsp;method explicitly because it is implemented by default, whereas for user-defined Python classes, we must define a custom&nbsp;<code>__str__()<\/code>&nbsp;method to get the string representation of the object; otherwise, it will return the object&#8217;s memory address.<\/p>\n\n\n\n<p>The address of the object is returned by the default implementation of the&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;functions on the object of the user-defined Python class. To return the string representation of the object, the custom&nbsp;<code>__str__()<\/code>&nbsp;and&nbsp;<code>__repr__()<\/code>&nbsp;methods must be defined within the class, and if&nbsp;<code>__str__()<\/code>&nbsp;is not defined, the object will call the&nbsp;<code>__repr__()<\/code>&nbsp;method.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-sort-vs-sorted\" rel=\"noreferrer noopener\">How Python sort() and sorted() methods are different and how they are used<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/seek-and-tell-in-python\" rel=\"noreferrer noopener\">How to move and locate the file pointer using seek() and tell() in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/abc-in-python\" rel=\"noreferrer noopener\">All about Python&#8217;s ABC &#8211; What is it and how to use it<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/tempfile-in-python\" rel=\"noreferrer noopener\">Generate and manipulate the temporary files using tempfile in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/super-in-python\" rel=\"noreferrer noopener\">How to use the super() function in Python classes<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/build-api-using-fastapi\" rel=\"noreferrer noopener\">Get started with FastAPI &#8211; A detailed guide<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/displaying-images-on-the-frontend-using-fastapi\" rel=\"noreferrer noopener\">Display images on the frontend using FastAPI<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the program output, we can represent Python strings in two ways. Python supports both informal and formal string representations. When we run the Python program to print the string, we get an informal representation of it in the output. The&nbsp;__str__&nbsp;method in Python is responsible for the informal representation of the object, which we can [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1062,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12,31],"class_list":["post-1060","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1060","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1060"}],"version-history":[{"count":3,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1060\/revisions"}],"predecessor-version":[{"id":1299,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1060\/revisions\/1299"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1062"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1060"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1060"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}