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)
- Docker: How to copy files to/from docker container - June 30, 2020
Anisble: ERROR! unexpected parameter type in action:
Fix- June 29, 2020
- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- 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