Open In App

How to change any data type into a String in Python?

Last Updated : 24 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. A string is a sequence of characters. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes.

Example : Creating strings in different ways :




# creating string using ' '
str1 = 'Welcome to the Geeks for Geeks !'
print(str1)
  
# creating string using " "
str2 = "Welcome Geek !"
print(str2)
  
# creating string using ''' '''
str3 = '''Welcome again'''
print(str3)


Output :

Welcome to the Geeks for Geeks!
Welcome Geek!
Welcome again

Changing any data type into a String

There are two ways for changing any data type into a String in Python :

  1. Using the str() function
  2. Using the __str__() function

Method 1 : Using the str() function
Any built-in data type can be converted into its string representation by the str() function. Built-in data type in python include:- int, float, complex, list, tuple, dict etc.
Syntax :

str(built-in data type)

Example :




# a is of type int
a = 10
print("Type before : ", type(a))
  
# converting the type from int to str
a1 = str(a)
print("Type after : ", type(a1))
  
# b is of type float
b = 10.10
print("\nType before : ", type(b))
  
# converting the type from float to str
b1 = str(b)
print("Type after : ", type(b1))
  
# type of c is list
c = [1, 2, 3]
print("\nType before :", type(c))
  
# converting the type from list to str
c1 = str(c)
print("Type after : ", type(c1))
  
# type of d is tuple
d = (1, 2, 3)
print("\nType before:-", type(d))
  
# converting the type from tuple to str
d1 = str(d)
print("Type after:-", type(d1))


Output:

Type before : <class 'int'>
Type after : <class 'str'>

Type before : <class 'float'>
Type after : <class 'str'>

Type before : <class 'list'>
Type after : <class 'str'>

Type before : <class 'tuple'>
Type after : <class 'str'>

Method 2 : Defining __str__() function for a user defined class to be converted to string representation. For a user defined class to be converted to string representation, __str__() function needs to be defined in it.

Example :




# class addition
class addition:
    def __init__(self):
        self.a = 10
        self.b = 10
  
    # defining __str__() function
    def __str__(self):
        return 'value of a = {} value of b = {}'.format(self.a, self.b)
  
# creating object ad
ad = addition()
print(str(ad))
  
# printing the type
print(type(str(ad)))


Output:

value of a =10 value of b =10
<class 'str'>


Similar Reads

Change the data type of a column or a Pandas Series
Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. Let’s see the program to change the data type of column or a Series in Pandas Dataframe.Method 1: Using DataFrame.astype() method. We can pass any Python, Numpy or Pandas datatype
3 min read
Change Data Type for one or more columns in Pandas Dataframe
Let's see How To Change Column Type in Pandas DataFrames, There are different ways of changing DataType for one or more columns in Pandas Dataframe. Change column type into string object using DataFrame.astype() DataFrame.astype() method is used to cast pandas object to a specified dtype. This function also provides the capability to convert any su
3 min read
Change the Data Type of the Given NumPy Array
NumPy arrays are homogenous, meaning all elements in a NumPy array are of the same data type and referred to as array type. You might want to change the data type of the NumPy array to perform some specific operations on the entire data set.  In this tutorial, we are going to see how to change the data type of the given NumPy array. We will use the
4 min read
Python - Change type of key in Dictionary list
Sometimes, while working with data, we can have a problem in which we require to change the type of particular keys' value in list of dictionary. This kind of problem can have application in data domains. Lets discuss certain ways in which this task can be performed. Input : test_list = [{'gfg': 9, 'best': (7, 2), 'is': '4'}, {'is': '2'}] Output :
6 min read
Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
In this post, we'll explore a Python pandas package feature. We frequently find queries about converting tick-by-tick data to OHLC (Open, High, Low and Close). Using pandas kit this can be done with minimum effort. The OHLC data is used over a unit of time (1 day, 1 hour etc.) to perform a technical analysis of price movement. The First Step: The f
2 min read
How to Change Column Type in PySpark Dataframe ?
In this article, we are going to see how to change the column type of pyspark dataframe. Creating dataframe for demonstration: Python Code # Create a spark session from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframe columns = [&quot;Name&quot;, &quot;Course_Name&quot;,
4 min read
Does Dark Data Have Any Worth In The Big Data World?
Big Data is the new oil in modern times!!! And those companies that can analyze this data for actionable insights are the new super-rich!!! More and more companies are understanding this fact and investing in Big Data Analytics. So much so that this number has reached 53% in 2017, which is a huge growth from 17% in 2015. But Big Data is of multiple
5 min read
How to convert categorical string data into numeric in Python?
The datasets have both numerical and categorical features. Categorical features refer to string data types and can be easily understood by human beings. However, machines cannot interpret the categorical data directly. Therefore, the categorical data must be converted into numerical data for further processing. There are many ways to convert catego
4 min read
Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using filter() + endswith() The combination of the above func
6 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Practice Tags :