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])
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
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Idiom | |
| Java | Native | |
| C | Absent | C has no methods; a program writes its own function that formats a struct into a buffer with snprintf. |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript; a class overrides toString, and template literals call it; no example file because it would repeat the JavaScript answer. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Native | Any 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. |
| SQL | Does not apply | SQL converts values with CAST; rows have no user methods. |
| Bash | Does not apply | All Bash values are strings. |
| PowerShell | Native | PowerShell objects are .NET objects with ToString; no example file because it would repeat the C# answer. |
| HTML | Does not apply | HTML has no objects with a string form. |
| CSS | Does not apply | CSS has no objects with a string form. |
| Regular expressions | Does not apply | Regular 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 ofObjectis the class name,@and the hash code in hexadecimal, which is useful only to tell objects apart. - C# works the same way. The default
ToStringreturns "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."6Displayis 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.
%vshows the fields,%+vadds their names and%#vshows Go syntax. AString() stringmethod changes%vand%s: "If an operand implements method String() string, that method will be invoked to convert the object to a string".2 - JavaScript calls
toStringwhen 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].
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"))
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__forprintandstr, and__repr__forrepr, the interactive prompt and the items of a container. {self.title!r}uses thereprof the field, so the string shows its quotes, and the debug form looks like the call that makes the object.- The default
__repr__ofobjectgives the class name and the address, in angle brackets. A list prints thereprof its items, not theirstr.
#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';
}
Dune (1965)
Read Dune (1965) 16
- Verdict: idiom. C++ has no string method on objects. The convention is an
operator<<forstd::ostream, whichstd::coutandstd::ostringstreamuse. - A string stream turns the display form into a
std::string, for code that needs a string and not a stream. std::formatandstd::printuse a different hook, a specialization ofstd::formatterfor the type; a type that has onlyoperator<<does not work with them.
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@"));
}
}
Book[title=Dune, year=1965]
Alien (1979)
Watch Alien (1979)
true
- Verdict: native.
Object.toStringgives every object a string form, andprintln, string concatenation andString.valueOfcall it. - A record generates
toStringfrom its components. A class keeps the default ofObject, 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;
Book { Title = Dune, Year = 1965 }
Alien (1979)
Watch Alien (1979)
Plain
- Verdict: native.
Object.ToStringgives every object a string form, andConsole.WriteLineand string interpolation call it. - A record generates
ToStringwith the type name and its properties in braces. A class keeps the default, the full name of its type, herePlain, until it overrides the method. IFormattableadds aToString(format, provider)overload for types such as numbers and dates, which need format strings and culture rules.
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));
Dune (1965)
Read Dune (1965)
[object Book]
[object Object]
{"title":"Dune","year":1965}
- Verdict: native.
Object.prototype.toStringgives every object a string form, andString(x)and template literals calltoString. - Without an override, the result is
"[object Object]". ASymbol.toStringTaggetter changes the type name in that default form. JSON.stringifygives 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)
}
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() stringmethod implementsfmt.Stringer, andfmtcalls it for%vand%sand inPrintln. - Without the method,
%vprints the fields in braces,%+vadds the field names, and%#vprints the value as Go syntax.%#vignoresString; aGoStringmethod can change it. - The display form and the debug form are two verbs of one package, not two methods that the type must write.
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]);
}
Dune (1965)
Book { title: "Dune", year: 1965 }
Book {
title: "Dune",
year: 1965,
}
11 [Book { title: "Dune", year: 1965 }]
- Verdict: stdlib.
Displayis the form for users, with{}, andDebugis the form for programmers, with{:?}. A type has neither until it derives or implements them. Debugcan be derived and shows the type name and every field.Displaycannot be derived; a type that implements it also getsto_stringfrom theToStringtrait.{:#?}pretty-prints the debug form on several lines. A vector prints theDebugform of its items.
Variations and related ideas
- 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'sFormatteroptions 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
reprof simple values comes close to a round trip, but it is not a contract. - Pretty-printing. Rust's
{:#?}, Python'spprintand Node.js'sutil.inspectsplit a large debug form over several lines with indentation.
Pitfalls
- The default form in user text. A message such as
"Order: " + orderprints 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)}`);
Order: [object Object]
Order: {"id":7,"total":12.5}
- Secrets in the string form. A generated
toStringprints 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
toStringthat 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
- Data model, The Python Language Reference, 3.3.1 Basic customization, object.__repr__ and object.__str__
- fmt package, Go standard library, Printing; type Stringer; type GoStringer
- Object (Java SE 21 & JDK 21), API documentation, toString
- Object.ToString Method, .NET API reference, Remarks
- Data classes, Kotlin documentation, Introduction
- Debug trait, Rust standard library, Description
- Display trait, Rust standard library, Description
- Object.prototype.toString(), JavaScript reference, MDN, Description
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag H38B5D Edit this page History Report an error Markdown