Python

How to convert string to int in Python

April 20, 2022

How to convert string to int in Python

In this article you will learn how to convert string to int in Python – in a very simple way that will make your life easier as a programmer

convert string to int in Python thumb

What’s up programmer, ok? Let’s learn more about converting variables in Python!

Let’s first create a situation where you get a number in string format

An easy way to do this is with the input function, which receives data passed from a string user.

So to convert this string to int, we can use a function called int

Which will convert this variable to an integer, let’s see a practical example:

numberToString = input ("Type a number ")

print(type(numberToString))

number = int(numberToString)

print(type(number))

Running this program and entering the number 5, we have the following output:

Type a number 5

<class 'str'>

<class 'int'>

See changing type of variable from str (string) to int (integer)

And this is how we convert a string to int with Python!

Remembering that it’s good to always treat the data before applying some logic, to ensure that that string is really an integer and doesn’t affect the flow of your software

Conclusion

In this article we learned how to convert string to int

Basically we must receive the string data by some means, here we use the input function

And apply int function on this value, which will do string to integer conversion in Python

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x