Type Casting in Python
Learn about type casting in Python and how to convert between different data types effectively in your programs.
10 min read
Beginner
Type casting
Type casting is used to convert data from one data type to another in Python. For example, you can convert the string value '98' to an integer value 98 using typecasting.
Let us have a look at various typecasting methods.
- int(): It is used to convert the passed value to an integer data type.
python
print(int('4'))
print(type(int('4'))This works for other data types as well. Let's see with a float.
python
print(int(4.0))
print(type(int(4.0)))- float(): It is used to convert the passed value to a float data type.
python
print(float(4))
print(float('4')- str(): It is used to convert the passed value to a string data type.
python
print(str(4))
print(str(4.02)String conversion can be done for an entire list or dictionary as well.
python
print(str(['1', '2', '3']))
print(str({'key':'val'}))- list(): It is used to convert the passed value to a list data type.
python
print(list('423'))
print(list((4, 2, 3)))
print(list({4, 2, 3}))- tuple(): It is used to convert the passed value to a tuple data type.
python
print(tuple('423'))
print(tuple([4, 2, 3]))
print(tuple({4, 2, 3}))- set(): It is used to convert the passed value to a set data type.
python
print(set('abc'))
print(set('aabc'))
print(set(['1', '2', '3', '3'])) # Duplicates will be removedTest your knowledge
🧠 Knowledge Check
1 / 10