What is dunder string function in Python?

🔹 What is __str__() in Python?

__str__() is a special (dunder) method in Python that defines the string representation of an object when print(object) or str(object) is called.


🔹 Why Use __str__()?

  • ✅ Makes objects human-readable when printed.
  • ✅ Useful for debugging (instead of memory addresses).
  • ✅ Customizes how an object is displayed in logs or Django Admin.

🔹 Example: Using __str__() in a Class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

person = Person("Alice", 30)
print(person)  # Calls __str__()

Output:

Alice is 30 years old

🚀 Now, print(person) displays a meaningful message instead of <__main__.Person object at 0x7f8b3e4c9d00>.


🔹 __str__() in Django Models

Django models use __str__() to define how objects appear in Django Admin and QuerySets.

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255)

    def __str__(self):
        return f"{self.title} by {self.author}"

Now, when you query:

book = Book.objects.create(title="Django Mastery", author="John Doe")
print(book)

Output in Django Admin / Shell:

Django Mastery by John Doe

🔹 __str__() vs __repr__()

Method Purpose
__str__() User-friendly string representation (used in print())
__repr__() Developer-friendly debugging representation (used in repr())

Example:

class Car:
    def __init__(self, model, year):
        self.model = model
        self.year = year

    def __str__(self):
        return f"{self.model} ({self.year})"

    def __repr__(self):
        return f"Car(model='{self.model}', year={self.year})"

car = Car("Tesla Model 3", 2024)
print(str(car))   # Calls __str__()
print(repr(car))  # Calls __repr__()

Output:

Tesla Model 3 (2024)
Car(model='Tesla Model 3', year=2024)

🚀 Summary

__str__() makes objects human-readable when printed.
✅ It is commonly used in Django models to make query results readable.
__repr__() is used for developer-friendly debugging.

Comments

57 responses to “What is dunder string function in Python?”

  1. Тркелу Avatar

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  2. nc27c Avatar
    nc27c

    amoxil tablets – https://combamoxi.com/ cheap amoxicillin pill

  3. my7jw Avatar

    diflucan 100mg brand – https://gpdifluca.com/# purchase forcan pill

  4. rg5ar Avatar

    cenforce 50mg without prescription – cheap cenforce 100mg order generic cenforce 100mg

  5. a5a7t Avatar

    vardenafil and tadalafil – ciltad gn cialis for sale brand

  6. 6hmqr Avatar

    buy cialis cheap fast delivery – strong tadafl maxim peptide tadalafil citrate

  7. 65hm4 Avatar

    50 mg sildenafil price – https://strongvpls.com/ street value viagra 100mg

  8. ConnieAcags Avatar

    I’ll certainly bring to be familiar with more. donde comprar kamagra en madrid

  9. 8ybya Avatar

    This website positively has all of the information and facts I needed to this case and didn’t identify who to ask. buy azithromycin pill

  10. ConnieAcags Avatar

    The thoroughness in this section is noteworthy. https://ursxdol.com/provigil-gn-pill-cnt/

  11. 7kbbz Avatar

    I’ll certainly carry back to be familiar with more. buy loratadine sale

  12. w430f Avatar

    More posts like this would persuade the online elbow-room more useful. aranitidine.com

  13. ConnieAcags Avatar

    This website exceedingly has all of the bumf and facts I needed there this case and didn’t positive who to ask. https://ondactone.com/spironolactone/

  14. Vytvorit bezplatn'y úcet Avatar

    Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  15. ConnieAcags Avatar

    More peace pieces like this would create the web better. http://www.fujiapuerbbs.com/home.php?mod=space&uid=3618552

  16. ConnieAcags Avatar

    buy dapagliflozin pills – this pill dapagliflozin

  17. ConnieAcags Avatar

    order xenical online – https://asacostat.com/ xenical 60mg generic

  18. ConnieAcags Avatar

    This is the tolerant of enter I turn up helpful. https://myrsporta.ru/forums/users/kedqm-2/

  19. Trade Cryptocurrencies on gate.com Avatar

    Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.

  20. Gevibam Avatar

    You can shelter yourself and your ancestors by being cautious when buying medicine online. Some pharmacy websites function legally and put forward convenience, secretiveness, rate savings and safeguards to purchasing medicines. buy in TerbinaPharmacy https://terbinafines.com/product/dilantin.html dilantin

  21. g1pk0 Avatar

    The thoroughness in this break down is noteworthy. TerbinaPharmacy

  22. play poker online free no sign up Avatar

    I’ll certainly return to review more.

  23. https://shahteru.ru/ Avatar

    Мне понравилась глубина исследования, проведенного автором, для подкрепления своих утверждений.

  24. школы Avatar

    This piece of writing will help the internet users for building up new webpage or even a weblog from start to end.

  25. Continue Avatar

    Эта статья является настоящим источником вдохновения и мотивации. Она не только предоставляет информацию, но и стимулирует к дальнейшему изучению темы. Большое спасибо автору за его старания в создании такого мотивирующего контента!

  26. вот здесь Avatar

    You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  27. моя ссылка Avatar

    I have learn a few excellent stuff here. Certainly value bookmarking for revisiting. I wonder how so much effort you place to make this type of excellent informative site.

  28. read this Avatar

    Hi! I just would like to offer you a big thumbs up for your excellent info you’ve got right here on this post. I am coming back to your web site for more soon.

  29. https://alexiada.ru/ Avatar

    Автор приводит разные аргументы и факты, позволяя читателям сделать собственные выводы.

  30. Cassandra Hill Avatar

    Я рад, что наткнулся на эту статью. Она содержит уникальные идеи и интересные точки зрения, которые позволяют глубже понять рассматриваемую тему. Очень познавательно и вдохновляюще!

  31. вот ссылка Avatar

    Hey there would you mind letting me know which web host you’re using? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a fair price? Thanks a lot, I appreciate it!

  32. https://wt-fan.ru/ Avatar

    Автор старается подойти к теме нейтрально, чтобы предоставить читателям полную картину.

  33. Visit This Link Avatar

    Автор предлагает аргументы, подкрепленные проверенными фактами и авторитетными источниками.

  34. digilider.ru Avatar

    Hi to every single one, it’s in fact a pleasant for me to visit this site, it consists of useful Information.

  35. https://techletter.ru/ Avatar

    Я оцениваю умение автора использовать разнообразные источники, чтобы подкрепить свои утверждения.

  36. digiscope.ru Avatar

    Отличная статья! Я бы хотел отметить ясность и логичность, с которыми автор представил информацию. Это помогло мне легко понять сложные концепции. Большое спасибо за столь прекрасную работу!

  37. https://digiscope.ru/ Avatar

    Very quickly this site will be famous amid all blog visitors, due to it’s good posts

  38. ОкПозвонок — Здоровье ваших суставов Avatar

    I am regular reader, how are you everybody? This post posted at this website is actually nice.

  39. https://everyweek.ru/ Avatar

    I like the helpful info you provide to your articles. I will bookmark your weblog and test once more here regularly. I am relatively sure I’ll learn many new stuff proper right here! Good luck for the following!

  40. кисти Avatar

    Статья представляет обобщенный взгляд на проблему, учитывая ее многогранные аспекты.

  41. https://koeimusou.ru/ Avatar

    Статья предлагает всесторонний обзор фактов и событий, оставляя читателям свободу интерпретации.

  42. болид ф1 Avatar

    I love it whenever people get together and share opinions. Great blog, keep it up!

  43. znamus Avatar

    I used to be suggested this blog via my cousin. I’m not positive whether this post is written through him as nobody else understand such distinct approximately my trouble. You’re amazing! Thank you!

  44. самолеты Avatar

    Автор предлагает систематический анализ проблемы, учитывая разные точки зрения.

  45. indycraft.ru Avatar

    Статья представляет анализ разных точек зрения на проблему, что помогает читателю получить полное представление о ней.

  46. https://fantastika-book.ru/ Avatar

    Это позволяет читателям анализировать представленные факты самостоятельно и сформировать свое собственное мнение.

  47. овощей Avatar

    Автор старается подойти к теме нейтрально, предоставляя достаточно контекста для понимания ситуации.

  48. ru - Avatar

    I like the valuable info you provide in your articles. I will bookmark your blog and take a look at again right here regularly. I’m reasonably certain I’ll be informed lots of new stuff proper right here! Good luck for the next!

  49. https://cendia.ru/ Avatar

    Хорошая статья, в которой автор предлагает различные точки зрения и аргументы.

  50. fantastika-book.ru Avatar

    Статья содержит обоснованные аргументы, подкрепленные фактами.

  51. https://eagi.kz/ Avatar

    Wow, awesome blog layout! How lengthy have you been running a blog for? you make blogging look easy. The full glance of your web site is fantastic, let alone the content material!

  52. https://trip-abroad.ru/ Avatar

    Статья содержит практические рекомендации, которые можно применить в реальной жизни для решения проблемы.

  53. https://v-teple.com/ Avatar

    Я оцениваю объективность и сбалансированность аргументации в статье.

  54. Бесплатный аккаунт на binance Avatar

    Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.info/da-DK/register?ref=V3MG69RO

  55. hoy777 Avatar

    Hoy777 es una opción más, no está mal. Hay bastantes juegos para elegir y los pagos son puntuales. Dale una probadita a hoy777.

  56. https://www.rkm.kz/ Avatar

    I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to construct my own blog and would like to know where u got this from. thank you

Leave a Reply

Your email address will not be published. Required fields are marked *