Today our python built-in function is int() which is useful for converting a number which is in string type in to integer. This is very much useful to club non int type which is a number(The number can be of any base like binary, nibble, oct and hex) to an integer.
Need of int() function in Python:
Some times when we are working with data, numbers are treated as strings and when we try to do some manipulation with other numbers we may get errors like "TypeError: cannot concatenate ‘str’ and ‘int’ objects". This error can be eliminated by converting a number in string type to an integer. In this post we will see on how to use int() python built-in function to do this.
Python int() function syntax:
From above syntax, 'number' should be a string or bytes or byte array which represents a number in a string type. And 'base' is optional and it is useful to convert this string from it’s base to integer. We can convert from any data type like string, hex, oct, binary to integer if it is represented by string type.
Examples: Let us start with int() function with some examples and see how we can use them in Python coding.
Example1: Convert a string to it’s .
Example2: Adding a string which is number to other number
My variables are
Adding two numbers in which one is in string format.
Example3: Converting from one form to other. Convert '0100' which can be a string, binary, nibble, oct, hex formats to integer
Related functions: chr(), str()
Latest posts by Surendra Anne (see all)
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018
- wget download a file to a directory in Linux/Unix - June 4, 2018
- GIT: How to compare two GIT branches? - June 3, 2018
- Online training on Linux Bash shell scripting - February 8, 2018