Python Type Conversion
Python has five standard Data Types. Sometimes it is necessary to convert values from one type to another. Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive program development.
Python String to Integer
The method int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:
Python String to float
Python Floats to Integers
Python Integers to Floats
Python Float to string
Converting to Tuples and Lists
- A list is a mutable ordered sequence of elements that is contained within square brackets [ ].
- A tuple is an immutable ordered sequence of elements contained within parentheses ( ).
You can use the methods list() and tuple() to convert the values passed to them into the list and tuple data type respectively.
Python List to Tuple
Python Tuple to List
While converting from string to int you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers.
You can see, the above code raised a ValueError exception if there is any digit that is not belong to decimal number system.
If you are ever unsure of the type of the particular object, you can use the type() function:
- Keywords in Python
- Python Operator - Types of Operators in Python
- Python Variables and Data Types
- Python Shallow and deep copy operations
- Python Mathematical Function
- Basic String Operations in Python
- Python Substring examples
- How to check if Python string contains another string
- Check if multiple strings exist in another string : Python
- Memory Management in Python
- Python Identity Operators
- What is a None value in Python?
- How to Install a Package in Python using PIP
- How to update/upgrade a package using pip?
- How to Uninstall a Package in Python using PIP
- How to call a system command from Python
- How to use f-string in Python
- Python Decorators (With Simple Examples)
- Python Timestamp Examples