How to Convert a String to Integer in Python
Table of Contents
In Python, like most programming languages, strings and numbers are treated very differently.
Strings are a sequence of characters whereas integers are whole numbers (positive or negative).
While coding in Python, you might need to convert a string to an integer.
For example, when you accept user input in a program, the input is usually in the form of a string but you need to convert it to an integer.
In this post, we'll learn how to convert a string to an integer in Python.
Convert a String to an Integer
The most straightforward way to convert a string to an integer is to use the int()
function.
This is a built-in function in Python that takes in your string and attempts to convert it to an integer for you.
It can technically take in any type of data, but for the purposes of this post, we'll only be using strings.
Let's start with our string:
PYTHONstring = "123"
Now we can pass in this string to the int()
function, to get an integer back:
PYTHONstring = "123"
integer = int(string)
print(integer)
BASH123
Conclusion
In this post, we learned how to convert a string to an integer in Python.
Simply use the int()
function and pass in the string you'd like converted.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript