Converting String to Integer In Python

5/5 - (2 votes)

Summary: To convert a string object to integer object use the float(string_input) method which typecasts the string input to a floating-point value.


❖ Introduction

Before learning how to convert a string object to a int object, let us understand what is type conversion in Python.

✎ The process of converting an object of a particular data type into another type is known as type conversion.

  • Type Conversion is of two types:
    • Implicit Type Conversion
    • Explicit Type Conversion

♻️ Implicit Type Conversion

When Python automatically converts one data type to another data type without the involvement of user, it is known as implicit type conversion.

Example: In the following code Python implicitly promotes a lower data type (integer) to a higher data type (float).

data_integer = 15  # integer object
data_float = 25.25  # float object
result = data_integer + data_float
print("result = ", result)
print("data type of result: ", type(result))


result =  40.25
data type of result:  <class 'float'>

♻️ Explicit Type Conversion

The type of conversion in which the user has to explicitly convert an object of one type to another type is known as explicit type conversion. You have to use built-in functions like int(), str(), float(), etc., to perform explicit type conversion.

✎ Note: Explicit type conversion is also known as typecasting.

Example: The following example how you can typecast an integer to a string.

value_int = 15
value_str = str(value_int)
print("value_int: ", value_int)
print("value_str: ", value_str)
print("Type of value_int: ", type(value_int))
print("Type of value_str: ", type(value_str))


value_int:  15
value_str:  15
Type of value_int:  <class 'int'>
Type of value_str:  <class 'str'>

Now that you know what is type conversion in Python, let us proceed with our topic – “How to convert a string object to a int object?”

Python int()

Python’s built-in int(value) function converts the argument value to an integer number. For example, int('42') converts the string value '42' into the integer number 42. The int() function on a float argument rounds down to the closest integer.

ArgumentvalueA Python object to be converted into an integer number. The value object must have an __int__() method that returns the associated integer number—otherwise a TypeError will be raised.
baseAn optional integer argument base to define the base of the numerical system in the value argument. If you set the base, the value argument must be a string. The base argument determines how the string argument is interpreted.
Return ValueintReturns an integer number after converting the input argument value using its required __int__() method for the conversion.

? Thus, you can simply convert a string value to an integer value using int('value').


value_str = '100'  # String object
value_int = int(value_str)  # converting to float
print("value_int: ", value_int)
print("value_str: ", value_str)
print("Type of value_int: ", type(value_int))
print("Type of value_str: ", type(value_str))


value_int:  100
value_str:  100
Type of value_int:  <class 'int'>
Type of value_str:  <class 'str'>

⚠️Caution: You can only convert a numeric-string, i.e., a string containing only numbers. If you try to typecast a text string to a float object, it will lead to ValueError.

value_str = 'Finxter'  # Text String Object
value_int = int(value_str)  # converting to float


Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/", line 2, in <module>
    value_int = int(value_str)  # converting to float
ValueError: invalid literal for int() with base 10: 'Finxter'

Python astype()

In Python, the NumPy module and the Pandas module have a method that converts one type of object into another. The name of this method is astype().

Convert String to Float using astype() in NumPy




import numpy
string_array = numpy.array(["25", "50", "100"])
print("Original array: ", string_array)
int_array = string_array.astype(numpy.int_)
print("Converted Array: ", int_array)
print("Type of elements within input string array: ", type(string_array[0]))
print("Type of elements within output float array: ", type(int_array[0]))


Original array:  ['25' '50' '100']
Converted Array:  [ 25  50 100]
Type of elements within input string array:  <class 'numpy.str_'>
Type of elements within output float array:  <class 'numpy.int32'>

Convert String to Float using astype() in Pandas


# importing pandas library
import pandas as pd
# dictionary
Data = {'Rate': ['4', '5', '9', '7']}
# create a dataframe
df = pd.DataFrame(Data)
# show dataframe
print("\nBefore Conversion: ")
# converting to float
df['Rate'] = df['Rate'].astype(int)
print("\nAfter Conversion: ")


0    4
1    5
2    9
3    7

Before Conversion: 
Rate    object
dtype: object

After Conversion: 
Rate    int32
dtype: object

Function to Convert String to Integer

You can use a function to convert a string input into an integer value as shown in the following program:


def convert(x, y, cast):
    x = cast(x)
    y = cast(y)
    return x, y
num1 = input("Enter 1st number: ")
num2 = input('Enter 2nd number: ')
a, b = convert(num1, num2, int)
print('Converting To Integer:')
res = a + b
print("Output: ", res)
print("Type of num1: ", type(num1))
print("Type of num2: ", type(num2))
print("Type of a: ", type(a))
print("Type of b: ", type(b))
print("Type(Output): ", type(res))


Enter 1st number: 25
Enter 2nd number: 45
Converting To Integer:
Output:  70
Type of num1:  <class 'str'>
Type of num2:  <class 'str'>
Type of a:  <class 'int'>
Type of b:  <class 'int'>
Type(Output):  <class 'int'>

If there are more than two variables that have to be converted, you can use a list as shown below.

def convert(list1, type_):
    for x in range(len(list1)):
        list1[x] = type_(list1[x])
# string inputs
a = '15'
b = '25'
c = '75'
li = [a, b, c]
print("Before Conversion: ", [type(number) for number in li])
convert(li, int)
print("After Conversion:", [type(number) for number in li])
print(li[0] + li[1] + li[2])


Before Conversion:  [<class 'str'>, <class 'str'>, <class 'str'>]
After Conversion: [<class 'int'>, <class 'int'>, <class 'int'>]
[15, 25, 75]

❖ Python Integer to String

Until now you learned how to convert a string object to a int object. Now, let us understand how we can deal the other way around, i.e., converting int to string.

Method 1: Using str()

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.


num_int = 2500
num_str = str(num_int)
print("num_str: ", num_str)
print("Type of num_float: ", type(num_int))
print("Type of num_str: ", type(num_str))


num_str:  2500
Type of num_float:  <class 'int'>
Type of num_str:  <class 'str'>

Method 2: Using String formatting – format() | f-string | %s

  • The format() method formats the specified value(s) and inserts them inside the string’s placeholder. Curly brackets ‘{} ’ are used to define the placeholder.
  • f-string is used as f’{inetger}’, where value inside curly bracket will help to convert the integer into string.
  • “%s”%integer, helps to convert the given integer to string by adding a value into Python string.
val_int = 55  # floating-point value
print("type of val_int: ", type(val_int))

# Using format()
val_str1 = "Year: {}".format(val_int)
print("type of val_str1: ", type(val_str1))

# Using f-string
val_str2 = f"{val_int}"
print("type of val_str2: ", type(val_int))

# Using %s
val_str3 = '%s' % val_int
print("type of val_str3: ", type(val_str3))


type of val_int:  <class 'int'>
type of val_str1:  <class 'str'>
type of val_str2:  <class 'int'>
type of val_str3:  <class 'str'>

❖ Conclusion

I hope this article helped you to understand how to convert a string object into a float object and vice-versa. Please stay tuned and subscribe for more exciting articles. Happy coding. ?‍?

Related Article: Python String to Float – A Simple Illustrated Guide

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!