Net-informations.com
SiteMap  | About    

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 int

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:

output

example

output

Python String to float

output

Python Floats to Integers

output

Python Integers to Floats

output

Python Float to string

Converting to Tuples and Lists

  1. A list is a mutable ordered sequence of elements that is contained within square brackets [ ].
  2. 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

output

Python Tuple to List

output

ValueError

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.

example

output

You can see, the above code raised a ValueError exception if there is any digit that is not belong to decimal number system.

output

If you are ever unsure of the type of the particular object, you can use the type() function:

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.