Open In App

How to convert string to integer in Python?

Last Updated : 10 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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

Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python - Convert Alternate String Character to Integer
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic method that strikes any programmer while performing t
5 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the "%s" keyword, the .format function or using f-string function. Below is the list
3 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [['4', '5', '7'], ['10', '8', '3']] Explanation : A
6 min read
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
Python Program to convert List of Integer to List of String
Given a List of Integers. The task is to convert them to a List of Strings. Examples: Input: [1, 12, 15, 21, 131]Output: ['1', '12', '15', '21', '131']Input: [0, 1, 11, 15, 58]Output: ['0', '1', '11', '15', '58']Method 1: Using map() [GFGTABS] Python3 # Python code to convert list of # string into sorted list of integer # List initialization list_i
5 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
Python Program to Convert a list of multiple integers into a single integer
Given a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890 There are multiple approaches possible to convert the given list into a single integer. Let's see each one by one. Approach #1 : Naive Method Simply iterate each element in
4 min read
Python | Ways to convert Boolean values to integer
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task. Convert Boolean values to integers using int() Converting bool to an integer using Python typecasting. C/C++ Code # Initialising Values bool_val = True # Printing initial Values print(
3 min read
Practice Tags :