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 :
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
- Using the
Method 1 : Using the
Any built-in data type can be converted into its string representation by the
str() function. Built-in data type in python include:-
str(built-in data type)
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.
value of a =10 value of b =10 <class 'str'>
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.