During programming in Python, We often need to convert a string to an integer in Python. This is because the standard input in Python is always read as a string independent of the type of input. To use integer data in our program when it is passed as space separated integers, we need to convert the string input to integer after splitting them using Python string split operation . In this article, we will look at how we can convert a string to integer without any errors and will implement the programs in Python.
How to convert string to integer in Python?
We can use int() function to convert a string to integer in Python. The string which has to be converted to integer is passed to the int() function as input argument and the function returns the corresponding integer value if the string passed as input is in proper format and no error occurs during conversion of the string to integer. We can convert a string to integer using int() function as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
1117
Output Integer is:
1117
When the input string is not in correct format, the int() function raises ValueError. This can be seen in the following example.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-3-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: 'aditya1117'
For which inputs ValueError will occur while converting a string to integer?
There may be several cases in which int() function will raise ValueError while converting a string to integer. Some of the cases are discussed below.
When we pass a string containing alphabets instead of numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-10-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int()
When the passed string contains any space characters along with numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "11 17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
11 17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-4-46d411efb04b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11 17'
When the passed string contains any punctuation marks such as period character (.) or comma (,) along with numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "11.17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
11.17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-5-97993fa7ba5b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11.17'
How to avoid ValueError while converting string to integer?
While converting a string to integer in Python, we can either preemptively check if the passed string consists of only the digits or not so that we can avoid the occurrence of error or we can use Python try except to handle the ValueError after it has been raised by the int() function. Both the methods have been discussed below.
We can use the isdigit() method to check if a string consists of only numeric characters or not. The isdigit() method when invoked on a string returns true if the string consists of only numeric digits. Otherwise it returns false. This can be implemented as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
Output:
Input String is:
1117
Output Integer is:
1117
If the input string contains characters other than numbers, output will be as follows.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
Output:
Input String is:
aditya1117
Input cannot be converted into integer.
To handle the ValueError after it has occurred, we can use exception handling using Python try except to handle the ValueError and show a proper message to the user as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
try:
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
Output:
Input String is:
1117
Output Integer is:
1117
If the input string contains characters other than numbers, output will be as follows.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
try:
myInt=int(myInput)
print("Output Integer is:")
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
Output:
Input String is:
aditya1117
Input cannot be converted into integer.
Conclusion
In this article, we have seen how we can convert a string to integer in Python and what problems can occur during conversion. We have also seen how to avoid and handle the ValueError raise by int() function during conversion of string to integer. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.