Python int convert exception

Python string to int and int to string

Python String To Int, Int To String

In this article, we will understand the conversion of Python String to Int and int to string conversion. In Python, the values are never implicitly type-casted. Let’s find out how to explicitly typecast variables.

1. Python String to int Conversion

Python int() method enables us to convert any value of the String type to an integer value.

string_num = '75846' print("The data type of the input variable is:\n") print(type(string_num)) result = int(string_num) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string to int:\n") print(result)
The data type of the input variable is: The data type of the input value after conversion: The converted variable from string to int: 75846

Conversion of Python String to int with a different base

Python also provides us with an efficient option of converting the numbers/values of the String type to integer values under a particular base in accordance with the number system.

int(string_value, base = val)
string_num = '100' print("The data type of the input variable is:\n") print(type(string_num)) print("Considering the input string number of base 8. ") result = int(string_num, base = 8) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string(base 8) to int:\n") print(result) print("Considering the input string number of base 16. ") result = int(string_num, base = 16) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string(base 16) to int:\n") print(result)

In the above snippet of code, we have converted ‘100’ to the integer value with base 8 and base 16 respectively.

The data type of the input variable is: Considering the input string number of base 8. The data type of the input value after conversion: The converted variable from string(base 8) to int: 64 Considering the input string number of base 16. The data type of the input value after conversion: The converted variable from string(base 16) to int: 256

ValueError Exception while Python String to int conversion

Scenario: If any of the input string contains a digit that does not belong to the decimal number system.

Читайте также:  What is header file in php

In the below example, if you wish to convert string ‘A’ to an integer value of A with base 16 and we do not pass base=16 as an argument to the int() method, then it will raise ValueError Exception.

Because even though ‘A‘ is a hexadecimal value, still as it does not belong to the decimal number system, it won’t consider A to be equivalent to decimal 10 unless and until we don’t pass base = 16 as an argument to the int() function.

string_num = 'A' print("The data type of the input variable is:\n") print(type(string_num)) result = int(string_num) print(type(result)) print("The converted variable from string(base 16) to int:\n") print(result)
The data type of the input variable is: Traceback (most recent call last): File "main.py", line 4, in result = int(string_num) ValueError: invalid literal for int() with base 10: 'A'

Converting a Python list of Integer to a list of String

Python list containing integer elements can be converted to a list of String values using int() method along with List Comprehension.

st_lst = ['121', '144', '111', '564'] res_lst = [int(x) for x in st_lst] print (res_lst)

2. Python int to String Conversion

Python str() method enables us to convert any value of the integer type to an String value.

int_num = 100 print("The data type of the input variable is:\n") print(type(int_num)) result = str(int_num) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from int to string:\n") print(result)
The data type of the input variable is: The data type of the input value after conversion: The converted variable from int to string: 100

Conclusion

In this article, we have understood the conversion of Python String to Integer and vice-versa.

References

Источник

Python String to Int, Int to String

Python String to Int, Int to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial, we will learn how to convert python String to int and int to String in python. In our previous tutorial we learned about Python List append function.

Python String to Int

If you read our previous tutorials, you may notice that at some time we used this conversion. Actually, this is necessary in many cases. For example, you are reading some data from a file, then it will be in String format and you will have to convert String to an int. Now, we will go straight to the code. If you want to convert a number that is represented in the string to int, you have to use int() function to do so. See the following example:

num = '123' # string data # print the type print('Type of num is :', type(num)) # convert using int() num = int(num) # print the type again print('Now, type of num is :', type(num)) 
Type of num is : Now, type of num is :

Python String To Int

Converting String to int from different base

If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output integer is always in base 10. Another thing you need to remember is that the given base must be in between 2 to 36. See the following example to understand the conversion of string to int with the base argument.

num = '123' # print the original string print('The original string :', num) # considering '123' be in base 10, convert it to base 10 print('Base 10 to base 10:', int(num)) # considering '123' be in base 8, convert it to base 10 print('Base 8 to base 10 :', int(num, base=8)) # considering '123' be in base 6, convert it to base 10 print('Base 6 to base 10 :', int(num, base=6)) 

The output of the following code will be Example of Python String to Int conversion Python Convert String To Int Base

ValueError when converting String to int

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. Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int() function. It will raise a ValueError exception if there is any digit that does not belong to the decimal number system. The following example will illustrate this exception while converting a string to int.

""" Scenario 1: The interpreter will not raise any exception but you get wrong data """ num = '12' # this is a hexadecimal value # the variable is considered as decimal value during conversion print('The value is :', int(num)) # the variable is considered as hexadecimal value during conversion print('Actual value is :', int(num, base=16)) """ Scenario 2: The interpreter will raise ValueError exception """ num = '1e' # this is a hexadecimal value # the variable is considered as hexadecimal value during conversion print('Actual value of \'1e\' is :', int(num, base=16)) # the variable is considered as decimal value during conversion print('The value is :', int(num)) # this will raise exception 
The value is : 12 Actual value is : 18 Actual value of '1e' is : 30 Traceback (most recent call last): File "/home/imtiaz/Desktop/str2int_exception.py", line 22, in print('The value is :', int(num)) # this will raise exception ValueError: invalid literal for int() with base 10: '1e' 

Python String To Int ValueError

Python int to String

Converting an int to string requires no effort or checking. You just use str() function to do the conversion. See the following example.

hexadecimalValue = 0x1eff print('Type of hexadecimalValue :', type(hexadecimalValue)) hexadecimalValue = str(hexadecimalValue) print('Type of hexadecimalValue now :', type(hexadecimalValue)) 
Type of hexadecimalValue : Type of hexadecimalValue now :

Python Int To String Conversion

That’s all about Python convert String to int and int to string conversion. Reference: Python Official Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

int() Function in Python

Python Certification Course: Master the essentials

To convert a specified value (any number or string) into an integer object, we use int() in python. The conversion of one data type into the other data type is known as type casting or type conversion.

Syntax of int() in Python

The syntax of the method, int() in Python is very simple:

The value parameter is required, but the base parameter is optional.

Parameters of int() in Python

The method — int() in python takes two parameters, one optional and the other required. The parameters given in int in python are:

  1. value: The value parameter is a required parameter. The value is the number or string to be converted into an integer object.
  2. base: The base parameter is optional. The default value specified is 10. The base-10 value resembles the number having base address 10 , i.e. decimal numbers.

We can specify the base type of the number other than 10 , such as

  • 8 for octal number (to convert octal number into an equivalent decimal number).
  • 16 for hexadecimal number (to convert a hexadecimal number into an equivalent decimal number).
  • 2 for binary number (to convert the binary number into an equivalent decimal number).

Return Values of int() in Python

The int in python returns the integer object value of the given string or floating number. If we do not give any parameter in the method, it will return 0 .

Exception of int() in Python

The int() in python raises an error whenever we pass a data type other than a string or an integer. For example, if we try to typecast a list using int in python. The following error will be printed:

This exception raised by int() in python is known as TypeError. Refer to this article’s topic — More Example to know more about the exceptions.

Example

Let us convert a floating-point number into an integer using the method int() in python.

What is int() in Python?

As we know, converting one data type into the other is known as type casting or type conversion.

We can convert any string into an integer using the built-in python method called int() method. The int() method takes a string or integer data type and converts the given data into an integer number.

what is int in python

How to Use int() in Python?

To convert a specified value (any number or string) into an integer object, we use int in python. The int in python is a built-in method that converts a string or a number into an integer. We can also use int in python to convert binary numbers to decimal numbers, hexadecimal numbers to decimal numbers, and octal numbers into decimal numbers.

The int method raises an error when a non-string or non-integer data type is given as a parameter. The error raised is termed as TypeError.

More Examples

Let us take a few examples to better understand the int method in python.

Example for Exception in int

Let us try to convert a list into an integer using int in python. As we have learned, we can only convert a string or a number into an integer.

How int() works in Python?

Let us try to convert a string into an integer using int in python.

How int() works for binary, octal, and hexadecimal?

Let us try to convert a binary, octal, and hexadecimal number into integer numbers using int in python.

int() for custom objects

Let us try to convert an object called Student into an integer number using int in python.

Internally the int in python calls int() method, which is the method of an object. So we can convert an object into an integer object using int in python.

We only need to override the int() method for a class to return an integer class.

Conclusion

  • To convert a specified value (any number or string) into an integer object, we use int in python.
  • The conversion of one data type into the other is known as type casting or type conversion.
  • The int() in python takes two parameters and returns an equivalent integer number. Its syntax is: int(value, base)
  • The value parameter is required, but the base parameter is optional.
  • Whenever we pass a data type other than a string or an integer, the int in python raises an error. The raised error is known as TypeError.

Learn More:

Источник

Оцените статью