• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Strings / String to Integer in Python

String to Integer in Python

Author: Aditya Raj
Last Updated: June 17, 2021

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. 

Related

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.

Enroll Now

Filed Under: Strings Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us