Programming Search⌘K

Conceptcore

String representation of an object

Also called string form, toString, __str__, __repr__, repr, Display trait, Debug trait, Stringer, ToString, printable representation, debug representation.

The string representation of an object is the text that a program gets when it prints the object or joins it to a string, often in two forms: a display form for users and a debug form for programmers.

Applies to
core-languages

Idea

A program often needs an object as text: to print it, to write it to a log, to show it in a debugger or a test failure, or to put it in a message. The string representation is the text that the object gives for these uses. Most languages call one method for it, such as toString, __str__ or String(), and give a default when the type does not define one.

There are two different readers of this text. A user wants a short, friendly form, such as Dune (1965). A programmer wants a form that shows the type and every field without doubt, such as Book(title='Dune', year=1965). Python, Rust and Go keep the two forms apart. Python's __repr__ computes "the “official” string representation of an object", while __str__ computes "the “informal” or nicely printable string representation".1 Java and C# have one method, so each type must choose.

How it works

The language calls the method in a fixed set of places. In Python, print, str() and f-strings call __str__, and repr(), the interactive prompt and the items of a list call __repr__:

class Book:
    def __init__(self, title, year):
        self.title, self.year = title, year

    def __repr__(self):
        return f"Book(title={self.title!r}, year={self.year!r})"

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


b = Book("Dune", 1965)
print(b)
print(repr(b))
print([b])
Output
Dune (1965)
Book(title='Dune', year=1965)
[Book(title='Dune', year=1965)]

The debug form uses the debug form of each field: !r puts the title in quotes, so 'Dune' is clearly a string. Python's advice for __repr__ is: "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value".1

The two forms have different rules:

Display form Debug form
Reader a user a programmer
Content the parts that matter to the user the type name and every field
Strings without quotes with quotes and escapes
Python __str__ __repr__
Rust Display, {} Debug, {:?}
Go String(), %v %+v and %#v, or GoString()
Default often none, or the debug form the type name and an address, or the fields

When a type gives only one form, the other falls back. Python: "If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required."1 Go's fmt calls String() for %v, but not for %#v.2

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaNative
CAbsentC has no methods; a program writes its own function that formats a struct into a buffer with snprintf.
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript; a class overrides toString, and template literals call it; no example file because it would repeat the JavaScript answer.
GoStandard library
RustStandard library
KotlinNativeAny declares toString, and a data class generates it from its properties; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applySQL converts values with CAST; rows have no user methods.
BashDoes not applyAll Bash values are strings.
PowerShellNativePowerShell objects are .NET objects with ToString; no example file because it would repeat the C# answer.
HTMLDoes not applyHTML has no objects with a string form.
CSSDoes not applyCSS has no objects with a string form.
Regular expressionsDoes not applyRegular expressions have no objects.
Language Verdict Mechanism
Python native __str__ and __repr__ on object; print, str, repr and f-strings call them
JavaScript native Object.prototype.toString; the default gives "[object Object]"
TypeScript native as JavaScript
Java native Object.toString; records generate it
Kotlin native Any.toString; data classes generate it
C# native Object.ToString; records generate it
Go stdlib fmt.Stringer and fmt.GoStringer; the verbs %v, %+v and %#v
Rust stdlib traits Display and Debug; Debug is derivable
C absent no methods; a program writes a function that fills a buffer with snprintf
C++ idiom operator<< for std::ostream, or a std::formatter specialization for std::format
Bash n/a all values are strings
PowerShell native .NET objects with ToString; the format system shows properties as a table or a list
SQL n/a CAST(x AS VARCHAR) converts values; no user types with methods in the standard
Regex n/a no objects
HTML n/a no objects
CSS n/a no objects
  • Java gives every object toString, and string concatenation calls it. The method should return "a concise but informative representation that is easy for a person to read".3 The default of Object is the class name, @ and the hash code in hexadecimal, which is useful only to tell objects apart.
  • C# works the same way. The default ToString returns "the fully qualified name of the object's type",4 and records generate a form with the type name and their properties.
  • Kotlin data classes generate the debug form: "toString() of the form "User(name=John, age=42)"".5
  • Rust has no default. Debug "should format the output in a programmer-facing, debugging context. Generally speaking, you should just derive a Debug implementation."6 Display is written by hand: "Display is similar to Debug, but Display is for user-facing output, and so cannot be derived."7
  • Go prints any value. %v shows the fields, %+v adds their names and %#v shows Go syntax. A String() string method changes %v and %s: "If an operand implements method String() string, that method will be invoked to convert the object to a string".2
  • JavaScript calls toString when an object becomes a string, for example in a template literal. MDN says that the method "is meant to be overridden by derived objects for custom type coercion logic."8 Without an override, all objects print as [object Object].
PythonGitHub
class Book:
    def __init__(self, title, year):
        self.title, self.year = title, year

    def __repr__(self):
        return f"Book(title={self.title!r}, year={self.year!r})"

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


class Plain:
    pass


b = Book("Dune", 1965)
print(b)
print(repr(b))
print([b])
print(f"{b} / {b!r}")
print(repr(Plain()).startswith("<__main__.Plain object at 0x"))
Output
Dune (1965)
Book(title='Dune', year=1965)
[Book(title='Dune', year=1965)]
Dune (1965) / Book(title='Dune', year=1965)
True
  • Verdict: native. Python has two forms: __str__ for print and str, and __repr__ for repr, the interactive prompt and the items of a container.
  • {self.title!r} uses the repr of the field, so the string shows its quotes, and the debug form looks like the call that makes the object.
  • The default __repr__ of object gives the class name and the address, in angle brackets. A list prints the repr of its items, not their str.
#include <iostream>
#include <sstream>
#include <string>

struct Book {
    std::string title;
    int year;
};

// The stream operator gives the display form to std::cout and string streams.
std::ostream& operator<<(std::ostream& os, const Book& b) {
    return os << b.title << " (" << b.year << ")";
}

int main() {
    Book b{"Dune", 1965};
    std::cout << b << '\n';
    std::ostringstream out;
    out << "Read " << b;
    std::string s = out.str();
    std::cout << s << ' ' << s.size() << '\n';
}
Output
Dune (1965)
Read Dune (1965) 16
  • Verdict: idiom. C++ has no string method on objects. The convention is an operator<< for std::ostream, which std::cout and std::ostringstream use.
  • A string stream turns the display form into a std::string, for code that needs a string and not a stream.
  • std::format and std::print use a different hook, a specialization of std::formatter for the type; a type that has only operator<< does not work with them.
JavaGitHub
public class Main {
    record Book(String title, int year) {}

    static final class Film {
        final String title;
        final int year;

        Film(String title, int year) {
            this.title = title;
            this.year = year;
        }

        @Override
        public String toString() {
            return title + " (" + year + ")";
        }
    }

    static final class Plain {}

    public static void main(String[] args) {
        System.out.println(new Book("Dune", 1965));
        System.out.println(new Film("Alien", 1979));
        System.out.println("Watch " + new Film("Alien", 1979));
        String s = new Plain().toString();
        System.out.println(s.startsWith("Main$Plain@"));
    }
}
Output
Book[title=Dune, year=1965]
Alien (1979)
Watch Alien (1979)
true
  • Verdict: native. Object.toString gives every object a string form, and println, string concatenation and String.valueOf call it.
  • A record generates toString from its components. A class keeps the default of Object, the class name, @ and the hash code in hexadecimal, until it overrides the method.
  • Java has one string form, so a class must choose between a form for users and a form for debugging.
using System;

var b = new Book("Dune", 1965);
Console.WriteLine(b);
Console.WriteLine(new Film("Alien", 1979));
Console.WriteLine($"Watch {new Film("Alien", 1979)}");
Console.WriteLine(new Plain());

record Book(string Title, int Year);

sealed class Film
{
    public Film(string title, int year) => (Title, Year) = (title, year);

    public string Title { get; }

    public int Year { get; }

    public override string ToString() => $"{Title} ({Year})";
}

sealed class Plain;
Output
Book { Title = Dune, Year = 1965 }
Alien (1979)
Watch Alien (1979)
Plain
  • Verdict: native. Object.ToString gives every object a string form, and Console.WriteLine and string interpolation call it.
  • A record generates ToString with the type name and its properties in braces. A class keeps the default, the full name of its type, here Plain, until it overrides the method.
  • IFormattable adds a ToString(format, provider) overload for types such as numbers and dates, which need format strings and culture rules.
JavaScriptGitHub
class Book {
  constructor(title, year) {
    this.title = title;
    this.year = year;
  }

  toString() {
    return `${this.title} (${this.year})`;
  }

  get [Symbol.toStringTag]() {
    return "Book";
  }
}

const b = new Book("Dune", 1965);
console.log(String(b));
console.log(`Read ${b}`);
console.log(Object.prototype.toString.call(b));
console.log(String({ title: "Dune" }));
console.log(JSON.stringify(b));
Output
Dune (1965)
Read Dune (1965)
[object Book]
[object Object]
{"title":"Dune","year":1965}
  • Verdict: native. Object.prototype.toString gives every object a string form, and String(x) and template literals call toString.
  • Without an override, the result is "[object Object]". A Symbol.toStringTag getter changes the type name in that default form.
  • JSON.stringify gives a second form that shows the fields, but it is a data format, not a description: it leaves out methods and fails on cycles.
package main

import "fmt"

type Book struct {
	Title string
	Year  int
}

// String is the display form; fmt calls it for %v and %s.
func (b Book) String() string {
	return fmt.Sprintf("%s (%d)", b.Title, b.Year)
}

type Plain struct {
	Title string
	Year  int
}

func main() {
	b := Book{"Dune", 1965}
	fmt.Println(b)
	fmt.Printf("%v | %s | %#v\n", b, b, b)
	p := Plain{"Dune", 1965}
	fmt.Printf("%v | %+v | %#v\n", p, p, p)
}
Output
Dune (1965)
Dune (1965) | Dune (1965) | main.Book{Title:"Dune", Year:1965}
{Dune 1965} | {Title:Dune Year:1965} | main.Plain{Title:"Dune", Year:1965}
  • Verdict: stdlib. A type with a String() string method implements fmt.Stringer, and fmt calls it for %v and %s and in Println.
  • Without the method, %v prints the fields in braces, %+v adds the field names, and %#v prints the value as Go syntax. %#v ignores String; a GoString method can change it.
  • The display form and the debug form are two verbs of one package, not two methods that the type must write.
RustGitHub
use std::fmt;

#[derive(Debug)]
struct Book {
    title: String,
    year: u16,
}

impl fmt::Display for Book {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.title, self.year)
    }
}

fn main() {
    let b = Book { title: "Dune".to_string(), year: 1965 };
    println!("{b}");
    println!("{b:?}");
    println!("{b:#?}");
    let s: String = b.to_string();
    println!("{} {:?}", s.len(), vec![&b]);
}
Output
Dune (1965)
Book { title: "Dune", year: 1965 }
Book {
    title: "Dune",
    year: 1965,
}
11 [Book { title: "Dune", year: 1965 }]
  • Verdict: stdlib. Display is the form for users, with {}, and Debug is the form for programmers, with {:?}. A type has neither until it derives or implements them.
  • Debug can be derived and shows the type name and every field. Display cannot be derived; a type that implements it also gets to_string from the ToString trait.
  • {:#?} pretty-prints the debug form on several lines. A vector prints the Debug form of its items.
  • Generated forms. Records in Java and C#, Kotlin data classes, Python dataclasses and Rust's #[derive(Debug)] write the debug form from the fields. A type then needs code only for the display form.
  • Format strings. C#'s IFormattable, Python's __format__ and Rust's Formatter options let the caller choose the form, such as a number of decimal places or a date pattern. The string representation is the form with no options.
  • Serialization. A string form for people is not a data format. To write an object and read it back, use object serialization, such as JSON, which has a defined grammar. Python's repr of simple values comes close to a round trip, but it is not a contract.
  • Pretty-printing. Rust's {:#?}, Python's pprint and Node.js's util.inspect split a large debug form over several lines with indentation.

Pitfalls

  • The default form in user text. A message such as "Order: " + order prints the class name, @ and a hexadecimal hash code in Java, and [object Object] in JavaScript when the type has no override:
const order = { id: 7, total: 12.5 };
console.log(`Order: ${order}`);
console.log(`Order: ${JSON.stringify(order)}`);
Output
Order: [object Object]
Order: {"id":7,"total":12.5}
  • Secrets in the string form. A generated toString prints every field, so a record with a password or a token puts it in every log line that prints the record. Override the method to hide such fields. See exposure of sensitive information.
  • Logic that parses the string form. Java says of toString: "The string output is not necessarily stable over time or across JVM invocations."3 A program that parses the form breaks when a field is added. Read the fields, or use a defined format.
  • An exception or a side effect in the method. Debuggers, loggers and error handlers call the method, often while something else is going wrong. A toString that reads a database, takes a lock or throws makes those tools fail.
  • Cycles. A generated form that prints every field never ends when two objects refer to each other, for example a parent with a list of children that each point back to the parent. Leave the back reference out of the form.

Cost

The string form builds a new string each time, so its cost grows with the size of the object and of its fields. A log statement such as log.debug("state: " + obj) builds the string even when debug logging is off; a logger that takes the object, or a lambda, builds it only when the message is written. Generated forms of large collections can be long; Python's reprlib gives a repr with a limit on the size.

History

JDK 1.0, released on January 23, 1996,9 put toString on java.lang.Object, next to equals and hashCode, so every Java object has a string form. Python's data model has two methods, __repr__ and __str__, for the two readers. Rust and Go later made the split part of the standard library: Rust with the traits Display and Debug, and Go with String() and the verbs of fmt.

References

  1. Data model, The Python Language Reference, 3.3.1 Basic customization, object.__repr__ and object.__str__
  2. fmt package, Go standard library, Printing; type Stringer; type GoStringer
  3. Object (Java SE 21 & JDK 21), API documentation, toString
  4. Object.ToString Method, .NET API reference, Remarks
  5. Data classes, Kotlin documentation, Introduction
  6. Debug trait, Rust standard library, Description
  7. Display trait, Rust standard library, Description
  8. Object.prototype.toString(), JavaScript reference, MDN, Description
  9. Java version history, Wikipedia, Release table

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/H38B5D/text.yaml