HOWTO · Python
tostring() Equivalent in Python
Learn which Python tools replace tostring(): use str() for conversion, join() for strings, f-strings or str.format() for templates, and __str__() for custom objects.
On this page
Python does not have a tostring() method; Java’s corresponding method is spelled toString(). Use the built-in str(value) when you need a string representation of one value. Use join() when you need to combine several strings, and use f-strings or str.format() when you are building a message. These operations produce display text; they are not a general-purpose serialization format.
Convert a value with str()
str() returns a string for numbers, collections, and most other Python objects. It is the direct answer to the question “What is the Python equivalent of tostring()?” For a collection, the result is its readable representation, including delimiters and the representations of its elements.
number = 123
values = [1, 2, 3]
print(str(number))
print(str(values))
Output:
123
[1, 2, 3]
The result of both calls is a str. Converting a dictionary or list this way does not create JSON, CSV, or another interchange format. Use a format-specific library when another program must read the data reliably.
Join strings and mixed values
Call join() on the separator, not on the list. Every item passed to join() must already be a string. This is the useful boundary that distinguishes joining from general conversion.
words = ["Hello", "world", "from", "Python"]
sentence = " ".join(words)
mixed = "|".join(map(str, [1, "two", None]))
print(sentence)
print(mixed)
Output:
Hello world from Python
1|two|None
For an iterable containing numbers or other objects, map(str, values) converts each item before joining it. A raw call such as ", ".join(["one", 2]) raises a TypeError, because join() does not implicitly convert non-string items.
Format values with f-strings
Use an f-string when a message contains values and the template is known where you write the code. Expressions inside braces are evaluated and converted as part of formatting. Format specifications can control precision, width, and other presentation details.
name = "Ada"
score = 3.14159
message = f"{name} scored {score:.2f}"
print(message)
Output:
Ada scored 3.14
F-strings were introduced in Python 3.6 and are available in the current Python 3.14 series. They are usually the clearest choice for a local, readable template, but they should not be used to serialize data for another system.
Use str.format() for templates
str.format() is useful when a template is stored separately, reused, or must support code that predates f-strings. It converts supplied values while replacing numbered or named fields.
item = "apple"
quantity = 5
message = "I have {quantity} {item}s.".format(quantity=quantity, item=item)
print(message)
Output:
I have 5 apples.
Prefer named fields when a template has several values; they make the relationship between each placeholder and its value easier to read. For new code with an inline template, an f-string is generally shorter.
Define __str__() for custom objects
Implement __str__() when your class needs a useful human-readable representation. Python calls it for str(instance) and when print() displays the instance. It must return a string, not a number or another object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
person = Person("Ada", 36)
print(str(person))
Output:
Ada (36)
Keep __str__() concise and useful to people. __repr__() has a different debugging and developer-facing purpose; defining one does not replace the other.
Limitations and method summary
Choose the operation that matches the result you need:
- Use
str(value)for one value or a readable representation of a collection. - Use
separator.join(strings)for combining strings, converting items first withmap(str, values)when needed. - Use f-strings for readable inline templates and
str.format()for reusable or separately stored templates. - Implement
__str__()when your own class needs a human-readable representation.
These methods do not guarantee a reversible or machine-readable representation. For JSON, use json.dumps() and handle types that JSON cannot represent. For a custom wire format, define its schema explicitly instead of relying on the output of str().
In short, replace a Java-style tostring() call with str(value), then choose join(), an f-string, str.format(), or __str__() when the task is specifically combining, formatting, or customizing text.