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 :
str1 = 'Welcome to the Geeks for Geeks !'
print (str1)
str2 = "Welcome Geek !"
print (str2)
str3 =
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 :
- Using the
str()
function
- 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 = 10
print ( "Type before : " , type (a))
a1 = str (a)
print ( "Type after : " , type (a1))
b = 10.10
print ( "\nType before : " , type (b))
b1 = str (b)
print ( "Type after : " , type (b1))
c = [ 1 , 2 , 3 ]
print ( "\nType before :" , type (c))
c1 = str (c)
print ( "Type after : " , type (c1))
d = ( 1 , 2 , 3 )
print ( "\nType before:-" , type (d))
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:
def __init__( self ):
self .a = 10
self .b = 10
def __str__( self ):
return 'value of a = {} value of b = {}' . format ( self .a, self .b)
ad = addition()
print ( str (ad))
print ( type ( str (ad)))
|
Output:
value of a =10 value of b =10
<class 'str'>
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Jul, 2020
Like Article
Save Article