What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

tostring() in Python? Equivalent Methods for Converting to String

  • Oct 03, 2022
  • 7 Minutes Read
tostring() in Python? Equivalent Methods for Converting to String

Python, like many other programming languages, supports 'typecasting,' or the conversion of an object from one data type to another. Now, this conversion can be Implicit and Explicit. While the Python Interpreter handles the Implicit Conversions automatically, the Explicit Conversions are performed by the user with the help of in-built functions.

Strings are an integrated and important part of any programming language. Hence, there are times when the need to typecast other data types into strings arises.  Before moving on, let's take a quick glance at strings in Python.

What are Strings in Python?

A string is defined as a sequence of characters, enclosed within quotation marks. These characters include everything: lowercase alphabets a-z, capital alphabets A-Z, numbers 0-9, all special characters like #, $, &, and blank spaces. Unlike other programming languages, Python allows you to use single quotation marks (' ') or double quotation marks (" ") to enclose strings.

Look at the code below to distinguish between strings and other data types (here objects):

#Strings in Python

a = 'Favtutor'
b = "1"
c = 4
print(a," ", type(a))
print(b, " ", type(b))
print(c, " ", type(c))


The type() method displays the type of object created.


Favtutor   <class 'str'>
1   <class 'str'>
4   <class 'int'>


Notice how the type() returns <class 'str'> for "1" while <class 'int'> for 4. This happened because 1 was enclosed within (" "), which made "1" to be a string even though it's a number.

What is tostring() in Python?

The tostring() is a method to convert other data types into strings. It returns the string representation of any object. Strings are common features, and each language has its own way of dealing with them. This method is offered by programming languages like Java. 

Python doesn't have a method named tostring(), but it offers other methods which do the task for you. Let's take a look at these methods.

6 Methods to Convert to Strings in Python

Python offers several methods, equivalent to tostring() method, to convert other objects into strings. These methods have their own advantages and applications. Let's begin with the list below:

01) Using str() method

The str() function in Python is considered a substitute for tostring() method offered by other programming languages. It is a built-in function to convert objects into strings. For instance, consider a variable holding an integer value, say 10.

var1 = 10


The type() statement will help us determine that the variable is an integer type.


<class 'int'>


Now, to convert this integer value into a string, all you need to do is pass this variable into str() function, as str(variableName). 

var1 = 10
print(var1, ' : ', type(var1))

# storing converted value into another variable
var = str(var1)
print(var + ' : ', type(var))
print(var1 + ' : ', type(var1))


Note the use of '+' operator with a string variable. The '+' operator is used to concatenate two strings together. I've also used the '+' operator with an integer type variable to depict the error. Output:

10  :  <class 'int'>
10 :  <class 'str'>
Traceback (most recent call last):
  File ".\temp.py", line 7, in <module>
    print(var1 + ' : ', type(var1))
TypeError: unsupported operand type(s) for +: 'int' and 'str'


Note the TypeError occurred due to the use of 'int' instead of 'str'.

Applying str() method on Lists:

The str() method can also be used on Lists to convert an object into a string. For example -

# declaring a list
a = [1, 2, 3, 4]
#converting list to str()
b = str(a)

print(b, ' : ', type(str(b)))



[1, 2, 3, 4]  :  <class 'str'>


Also, note that directly using str(a) or str(var) will not change the object type to string. The str() function 'converts' the object into a String and 'returns' the value. Hence, it always needs a reference object to store that value.

02) Using the format method

As seen above, the major concern while dealing with strings is while printing them. Python offers a format method, that takes in variables and inputs them into strings. Since these return a string, they can either be stored in a variable or directly printed using the print() function.

The format method is generally used to ease out displaying multiple values/variables (objects other than String). The basic syntax of the format method is:


Let's take an example to display the use of the format method:

# declaring multiple variables
currentYear = 2022
Years = [2019, 2020, 2021, 2022]
var = "Years"

# Using format method to create a string of multiple variables
strings = "A list of {} is {}.".format(var, Years)

# Using format method on integer variable
print("The current year is: {}".format(currentYear))


I've used the format method while calling variables(all objects).


A list of Years is [2019, 2020, 2021, 2022].
The current year is: 2022


Note that the use of the format method only facilitates while displaying strings, it doesn't actually convert an object into a string until it is stored in another variable. Take the example below-

# declaring multiple variables
var = 2022

# converting to strings
var1 = "{}".format(var)

# Note that variable is not typecasted into String
print("The variable: ", var, " : ", type(var))

# Printing the new typecasted variable 
print("The converted variable: ", var1, " : ", type(var1))


The '{}' brackets represent the space for variable values to be printed. Remember that the variable names in format() should follow the sequence of '{}' brackets.


The variable:  2022  :  <class 'int'>
The converted variable:  2022  :  <class 'str'>


Applying the format method hasn't made any change in the original variable. Instead, this method creates a copy of it.

Also, you can also index the variables in order to use them again without repeating the code.

For example:

# declaring variables
a = 7
b = 5
c = "Minutes"
    "This is a {1} {2} read article and it takes {0} {2} to try the code.".format(
        a, b, c


Note that similar to lists' and arrays' indexing, here also the indexing begins with 0.


This is a 5 Minutes read article and it takes 7 Minutes to try the code. 


You can observe the reuse of variables by using their index number between the '{}' brackets.

03) Using __str__() method

The __str__() method is an in-built method in Python to convert other objects' data types into Strings. The str() function and print() function internally calls for __str__() method to do the task. This method when called on by default displays some information about the object. Let's take an example:

# declaring class
class cards:
    def __init__(self, num) -> None:
        self.num = num

# default implementation of __str__()
card = cards(1)


However, the default __str__() method does not transform the object to a string and instead displays object information in a human-readable format.


<__main__.cards object at 0x0000021FB179DC48>


Let's move on to another example of using __str__() method. While using this method with class, we need to describe the __str__() method in order for it to serve the purpose. 

# declaring class
class cards:
    def __init__(self, num) -> None:
        self.num = num

# declaring __str__() method def __str__(self) -> str: return "Card number is: {}".format(self.num) card = cards(1) print(card.__str__())


We can use any other typecasting method (say str(), format() , f-string() or others) in the return statement. This makes it a class method for returning strings.


Card number is: 1


04) Using f-strings

f-strings are another form of the format method. These are adopted by new Python versions since they provide more ease and readability than the format method. In the format method, we had to use '{}'  in place of variable values and put the variables strictly in the required sequence. However, for longer strings with multiple variables, it was hard to recall the variables' sequence. Hence the f-strings came into existence. Using f-strings you can directly use the variable within the string by enclosing them between '{}'. Hence, no hassle to recall the sequence again and again!!

Let's take a look at the syntax for f-strings: 

f' text {variableName} text {variableName}'

For example:

# declaring variables 
num = 5
name = "FavTutor"
use = "convert objects to strings."

# Using f-strings
final = f'This {name} article has {num} methods to {use}'


This method has increased the readability of code in format strings in Python.


This FavTutor article has 5 methods to convert objects to strings.


The above example displayed the basic use of f-strings. To convert objects into strings, f-strings can be used as-

# declaring variables
num = 5
name = "FavTutor"
use = "convert objects to strings."

# Using f-strings
articles = f"{num}"
print("Number of articles: " + articles)
print("Number: ", num, " : ", type(num))


Check out how the types of articles and num differ due to f-strings -


Number of articles: 5
<class 'str'>
Number:  5  :  <class 'int'>


05) Using repr() method

The repr() method returns a string containing an object's printed representation. It takes an object as input and returns a string. It doesn't actually convert the object into a string but returns a string in printable format. Its syntax is very similar to str(), as:


Let's take a look at the example below:

#declaring variables
    a = 10
    b = 20
    c = 30
    # Using repr() method
    d = repr(a)
    print(d, ' ', type(d))
    print(repr(b), ' ', type(repr(b)))


By using repr() method, the data type of the actual object, passed as a parameter, doesn't change.


10   <class 'str'>
20   <class 'str'>


There's a lot of confusion between the repr() method and the str() method. Similarly, the methods __repr__() and __str__() method are also quite similar but with a slight difference. While the __str__() method returns a more human-readable format, the __repr__() method returns a more machine-friendly string format.

06) Using '%s'

Although not widely recognized, this approach is a simple means of representing (converting) things into strings. If you're familiar with "%s" in programming languages like C and C++, you'll know that it's used to represent strings (one line). It employs the modulo operator (%) and follows a basic syntax:

"%s" % variableName


#declaring variables
   a = 10
   b = 20
   # using %s to convert variable b into string
   string_b = '%s' % b
   # directly calling %s in the print function
   print('%s' % a , type('%s'%a))
   # calling the new obtained string_b variable
   print(string_b, type(string_b))


I've displayed both examples, i.e. calling "%s" directly in print() and storing the value in a variable. Apart from integers, "%s" can also be used with lists.


10 <class 'str'>
        20 <class 'str'>


Apart from variables (integer objects), this method can also be used with other objects, like lists and dictionaries.

# declaring variables
    c = [1, 2, 3, 4]
    d = {1: 43, 2: 34}
    # using %s with list c
    print(c, type("%s" % c))
    # using %s with dictionary d
    print(d, type("%s" % d))


This is also an easy method to represent objects into strings while dealing with printing the objects.


[1, 2, 3, 4] <class 'str'>
{1: 43, 2: 34} <class 'str'>           


Also, here are some methods to convert int to string in python.


Strings are an important part of the software. There are many problems that require typecasting of data (objects) into strings. Python offers many methods to convert objects into strings. Some of them are listed above. These methods return string representations of these objects and provide the facility to print multiple variables with ease. Some of these methods can also be declared according to the user. Try these methods and find out the best method for you!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Mradula Mittal
I'm Mradula Mittal, a tech community enthusiast with a knack for content writing. Always eager to learn more about Python and Machine Learning. Having an analytical brain, I'm particular about my research and writing. I live by the motto "the more you share, the more you learn" and being a techie, it's fun to learn, create and share.