Learn Python – How To Parse String to Float or Int

 
To transform a string into Int or Float in Python, simply put, can be done using the following lines:


These lines work perfectly when you know exactly the origin of your data. At times, however, you don’t know the data type of the string. We will complete the answer addressing some of these different cases.
 

Checking if the string value is an int or float in Python

If you use the conversion method for int in a string that was decimal values, it will send an error. Thus, we can use the code below to turn a string into int or float:


Be very careful with this code because it will be mixing two types of numbers, which can cause problems in later operations using them.
 

To convert a float to int

If necessary subsequently conversion of a float created into an integer you can use this line:


Here we see what it does:


 

To round float in the transformation to int

The above method simply ignores the decimal values. To take them into account is necessary to use the following:


This shows to the system that it has to do a round operation. It will always round down. If you wanted a rounding up, do something like this:


 

ENJOYING THIS POST?

Get More Benefits With LiveEdu Pro

How to transform a string list

If you know exactly the type of data inside of the string, and it comes in a list format, you can make the transformation of all at once, using the code below:


It also works with conversion to int.

If you know more ways how to make this conversion, share in the comments area below.

Now that you discovered the answer to this question and want to explore other, you can check our videos about learning Python. Below are some examples:

You can also subscribe to some channels that broadcast in Python, such as the following ones:

Zakko

jailbot

 
Another interesting way to find out cool things about Python is to access our project page!

 

LiveEdu Pro
Check Out the LiveEdu Pro Subscription

  • Kevin Rodger

    Great article. Thanks

Read previous post:
String e Substring (1)
JavaScript – Como verificar se uma String contém outra Substring?

Uma das tarefas mais comuns  em qualquer linguagem de programação, é determinar se existe uma determinada substring dentro de uma...

Close