String to int in PythonIn this tutorial, we will learn the ways of converting a string to integer in Python- Let us have a look at an example before proceeding- Output: <class 'str'> <class 'int'> In the above example, we have declared the variables ‘a’ and ‘b’ with a string and an integer value respectively. We can verify their data types using type(). The question that arises here is why do we need to convert a string to an integer. The following program illustrates the same- Output: res = value_a * value_b TypeError: can't multiply sequence by non-int of type 'str' Since it generates this type of error, this is the reason that we must convert the string values to integers so that we can easily proceed with the operations. It’s time to have a look at the first program that demonstrates converting a string to an integer. Output: <class 'str'> <class 'int'> 17 <class 'int'> Explanation: Let’s see the explanation of the above program-
Approach-2In the next example, we will go for an indirect approach of converting a string to an integer. The following program shows how it can be done- Output: <class 'str'> <class 'str'> The sum of value_a and value_b is 126.0 Explanation: Let us understand what we have done in the above program-
Approach-3:In the last program, we will discuss one more scenario of converting string to int in Python. Here we will see how we can convert a number present as a string value to base 10 when it is on different bases. The following program illustrates the same- Output: The value of num_value is: 234 The value of num_value from base 10 to base 10 is: 234 The value of num_value from base 8 to base 10 is: 156 The value of num_value base 6 to base 10 is: 94 Explanation: It’s time to have a glance at the explanation of the above program.
ConclusionIn this tutorial, we learned the different ways of converting a string to an int value. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263396.html