Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Int using try/except in Python

So I'm pretty stumped on how to convert a string into an int using the try/except function. Does anyone know a simple function on how to do this? I feel like I'm still a little hazy on string and ints. I'm pretty confident that ints are related to numbers. Strings...not so much.

like image 717
user1039163 Avatar asked Nov 10 '11 06:11

user1039163


People also ask

How do you convert string to int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you check if a string can be converted to int Python?

To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits. In addition, it checks if the characters present in the string are digits or not.

How do you convert a float to an int in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.


1 Answers

It is important to be specific about what exception you're trying to catch when using a try/except block.

string = "abcd" try:     string_int = int(string)     print(string_int) except ValueError:     # Handle the exception     print('Please enter an integer') 

Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.

like image 158
Nathan Jones Avatar answered Sep 23 '22 23:09

Nathan Jones