The Wayback Machine - https://web.archive.org/web/20241127054403/https://www.geeksforgeeks.org/how-to-convert-string-to-integer-in-python/
Open In App

How to convert string to integer in Python?

Last Updated : 10 Jul, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, a string can be converted into an integer using the following methods :

Method 1: Using built-in int() function: 

If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer.

Syntax : int(string, base)

Parameter : This function take following parameters :

  • string : consists of 1’s, 0’s or hexadecimal ,octal digits etc.
     
  • base : (integer value) base of the number.

Returns : Returns an integer value, which is equivalent 
of string in the given base. 

Code :

Python3




# Initialising a string 
# with decimal value
string = "100"
  
# Show the Data type
print(type(string))
  
# Converting string into int
string_to_int = int(string)
  
# Show the Data type
print(type(string_to_int))


Output:

<class 'str'>
<class 'int'>

By default, int() expect that the string argument represents a decimal integer. Assuming, in any case, you pass a hexadecimal string to int(), then it will show ValueError. In such cases, you can specify the base of the number in the string.

Code:

Python3




# Initialising a string
# with hexadecimal value
string = "0x12F"
  
# Show the Data type
print(type(string))
  
# Converting hexadecimal 
# string into int
string_to_int = int(string, 
                    base=16)
# Show the Data type
print(type(string_to_int))


Output:

<class 'str'>
<class 'int'>

Method 2: Using user-defined function: 

 We can also convert a string into an int by creating our own user-defined function.

Approach: 

  • we’ll check, if the number has any “-” sign or not, for if it is a negative number it will contain “-” sign. If it contains “-” sign, then we will start our conversion from the second position which contains numbers.
  • Any number, suppose 321, can be written in the structure : 10**2 * 3 + 10**1*2 + 10**0*1
  • Similarly, we split each of the input number using ord(argument), ord(‘0’) will return 48, ord(‘1’) returns 49 and so forth.
  • The logic here is that ord(‘1’) – ord(‘0) = 1, ord(‘2’) – ord(‘0’) = 2 and so on which gives us the significant  number to be fetched from the given input number.
  • Finally, the result we get from the function is an Integral number which we changed over from the given string.

Code:

Python3




# User-defined function to 
# convert a string into integer
def string_to_int(input_string):
    
  output_int = 0
    
  # Check if the number contains
  # any minus sign or not, 
  # i.e. is it a negative number or not. 
  # If it contains in the first
  # position in a minus sign,
  # we start our conversion 
  # from the second position which
  # contains numbers.
  if input_string[0] == '-' :
    starting_idx = 1
    check_negative = True
      
  else:
    starting_idx = 0
    check_negative = False
      
  for i in range(starting_idx, len(input_string)):
      
    # calculate the place value for 
    # the respective digit
    place_value = 10**(len(input_string) - (i+1))
      
    # calculate digit value
    # ord() function gives Ascii value
    digit_value = ord(input_string[i]) - ord('0')
      
    # calculating the final integer value
    output_int += place_value * digit_value
      
  # if check_negative is true 
  # then final integer value 
  # is multiplied by -1
  if check_negative :
    return -1 * output_int
  else:
    return output_int
  
# Driver code
if __name__ == "__main__" : 
    
  string = "554"
  
  # function call
  x = string_to_int(string)
  
  # Show the Data type
  print(type(x))
  
  string = "123"
  
  # Show the Data type
  print(type(string_to_int(string))) 
  
  string = "-123"
  
  # Show the Data type
  print(type(string_to_int(string)))


Output:

<class 'int'>
<class 'int'>
<class 'int'>


Previous Article
Next Article

Similar Reads

Convert Hex String To Integer in Python
Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this task. In this article, we will explore various method
2 min read
Convert integer to string in Python
In this article, we’ll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function. Using str() FunctionThe str() function is the simplest and most commonly used method to convert an integer to a string. [GFGTABS] Python n = 42 # Convert integer to string s = str(n) print(
2 min read
How to Convert String to Integer in Pandas DataFrame?
Let's see methods to convert string to an integer in Pandas DataFrame: Method 1: Use of Series.astype() method. Syntax: Series.astype(dtype, copy=True, errors=’raise’) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).copy: Makes a copy of dataframe/series.errors: Erro
3 min read
How to convert signed to unsigned integer in Python ?
Python contains built-in numeric data types as int(integers), float, and complex. Compared to C programming, Python does not have signed and unsigned integers as data types. There is no need to specify the data types for variables in python as the interpreter itself predicts the variable data type based on the value assigned to that variable. The i
2 min read
How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately. Here, we deal with a special date objec
2 min read
How to Convert Integer to Datetime in Pandas DataFrame?
Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check data type for the 'Dates' column is Integer. Python
2 min read
Convert IP address to integer and vice versa
We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks. The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) usually won’t accept objects from ipaddress module
2 min read
How to Fix: ValueError: cannot convert float NaN to integer
In this article we will discuss how to fix the value error - cannot convert float NaN to integer in Python. In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer. Let's see the error and explore the methods to deal with it. Dataset in use: L
3 min read
Convert a Dataframe Column to Integer in Pandas
When we use data in Python it often involves using Pandas, a powerful library for data manipulation and analysis. When dealing with DataFrames, it's common to encounter columns with data types that need to be converted for further analysis or visualization. One frequent task is converting a column to an integer type. In this article, we'll explore
4 min read
Check If String is Integer in Python
In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding. Example: Input2 : "geeksforgeeks"Output2 : geeksforgeeks is not an IntigerExplanation : "geeksforgeeks" is a string but cannot be converted
4 min read
Python Hex String to Integer List
Hexadecimal strings are commonly encountered when working with low-level programming, networking, or cryptographic applications. In Python, converting a hex string to an integer array or list is a frequent task. In this article, we'll explore some different methods to achieve this conversion. Hex String To Integer Array We change a Hex string into
3 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Print the largest integer formed by inserting digit X in given string
Given a string S of size N representing a large integer value, and a positive digit X, the task is to print the largest integer formed by inserting the digit X in the string S. Examples: Input: S = "99", X = 9Output: 999Explanation: The largest number that can be formed is 999 after inserting 9 into "99". Input: S = "-13", X = 2Output: -123Explanat
7 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple,
4 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python | sympy.Integer() method
With the help of sympy.Integer() method, we can convert the floating point to integer values and this method very efficient in term of memory if we want to save integer value. Syntax : sympy.Integer() Return : Return integer value. Example #1 : In this example we can see that by using sympy.Integer() method, we are able to convert the floating valu
1 min read
Check the equality of integer division and math.floor() of Regular division in Python
For large quotients, floor division (//) doesn't seem to be necessarily equal to the floor of regular division (math.floor(a/b)) Examples: Input : 269792703866060742 // 3 Output : 89930901288686914 Input : math.floor(269792703866060742 / 3) Output : 89930901288686912 In the above examples, the output for floor division(//) is 89930901288686914 and
2 min read
Python EasyGUI – Integer Box
Integer Box : It is used to get the integer input from the user, input should be integer input not string which happens in enter box. It displays the title, message to be displayed, place to enter a integer input and a pair of "Ok", "Cancel" button which is used confirm the input. We can set some default integer value to the place where user enter
3 min read
Create integer variable by assigning binary value in Python
Given a binary value and our task is to create integer variables and assign values in binary format. To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. Input: Var = 0b1010 Output: 10 Input: Var = 0b11001 Output: 25 Note: To p
2 min read
Python datetime to integer timestamp
In this article, we are going to see how to convert python DateTime to integer timestamp. The timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That zero moment is known as the epoch. First, we will get the current time or explicitly mention the required date and time we want the timest
3 min read
What is the maximum possible value of an integer in Python ?
Consider below Python program. C/C++ Code # A Python program to demonstrate that we can store # large numbers in Python x = 10000000000000000000000000000000000000000000 x = x + 1 print (x) Output : 10000000000000000000000000000000000000000001 In Python, value of an integer is not restricted by the number of bits and can expand to the limit of the a
2 min read
Zerodivisionerror Integer by Zero in Python
Python, a versatile and powerful programming language, is widely used for various applications, from web development to data analysis. One common issue that developers often encounter is the ZeroDivisionError, which occurs when attempting to divide a number by zero. In this article, we will explore the causes of this error and provide practical sol
3 min read
Converting an Integer to Ascii Characters in Python
In Python, working with integers and characters is a common task, and there are various methods to convert an integer to ASCII characters. ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents text in computers. In this article, we will explore some simple and commonly used methods for convertin
3 min read
How to take integer input in Python?
In this post, We will see how to take integer input in Python. As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function. Let us see the examples: Example 1: [GFGTABS] Python # take input from user
3 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Convert binary to string using Python
Data conversion has always been widely used utility and one among them can be the conversion of a binary equivalent to its string. Let’s discuss certain ways in which this can be done. Method #1:The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is
4 min read
Convert date string to timestamp in Python
The Most Common way we use to store dates and times into a Database is in the form of a timestamp. date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are: Using timetuple()U
2 min read
Convert string to title case in Python
Title case is a style of writing that is used for the titles of articles, books, movies, and other works. The rules for writing in title case are: 1) Always capitalize the first word. 2) Capitalize all words except the following parts of speech: articles - a, an, the coordinating conjunctions - and, but, for, nor, or, so, yet short prepositions - t
2 min read
Convert String to Long in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long. Converting String to long A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Py
1 min read
Practice Tags :
three90RightbarBannerImg