How to change any datatype to String in Python

In this post, we are going to learn how to change any datatype to String in Python by using the built-in method of Python. In Python str() and __str__() functions are used to convert any data type to string in python. We will understand both functions in detail with examples

1. Str() to change any datatype to String in Python


The Python str() function changes values of any type(int, float, list, tuple, dictionary, complex) to string. We will pass the given data type as a parameter to this function.

Syntax

str(value,encoding,error)

Parameters

  • value: The value of giving datatype we have to convert into a string.
  • Encoding: The encoding we have to the default value is UTF-8.
  • Error : We to specify the error we want to raise if conversion fail

1.1 Str() to Convert list to string in Python


In this python program example, we will understand how to convert a list to a string in python by using the str() method. We have used the str() function along with list comprehension to convert all list elements to strings. The Python type() function is used to check the data type of the variable.

mylist = [3,6,9,12,15,16]

print('Type before conversion:',type(mylist))

listtoStr = " ".join(str(item) for item in mylist)

print(listtoStr)
print(type(listtoStr))


Output

Type before conversion : <class 'list'>

3 6 9 12 15 16

<class 'str'>

1.2 Str() to Convert variable to a string python


In this python program example, we have two variables num,num2 that we have converted to a string by using the Str() method.

num = 3
num2 = 6


print(type(num))
print(type(num2))


numtoStr = str(num)
num2Str = str(num2)

print('\nint to string:')
print(type(numtoStr))
print(type(num2Str))

Output

<class 'int'>
<class 'int'>

 int to string:
<class 'str'>
<class 'str'>

2. __str__() convert python objects to string


The __Str()__ function is used to represent user-defined class objects to strings. To convert a user-defined class to a string. We have to define the __str()__ function in the class.

In the below example we have to define __str()__ function in class “Fruits” that takes a class constructor as a parameter and returns the name details of fruits its name and prize.


class Fruits:
    def __init__(self, name, prize):
        self.name = name
        self.prize = prize

    def __str__(self):
        return '{self.name} fruit'.format(self=self)



class Fruits:
    def __init__(self,name,prize):
        self.name = name
        self.prize = prize
  
    
    def __str__(self):
        return 'name = {}, prize = {}'.format(self.name, self.prize)
  

fruits = Fruits('Apple',15)
print(str(fruits))
  

print(type(str(fruits)))

Output

name = apple, prize = 15
<class 'str'>