Python Convert String to Int

1. Introduction

In Python programming, converting data types is a fundamental operation. Specifically, transforming a string that represents a number into an integer is a frequent necessity, especially when handling user input or parsing text files. This blog post focuses on how to perform this conversion in Python effectively.

Definition

String to integer conversion in Python is the process of transforming a string object that consists of digit characters (e.g., '123') into an integer data type (e.g., 123). This is typically accomplished using the int() function, which takes a string argument and returns its integer equivalent.

2. Program Steps

1. Have a string that represents a number.

2. Use the int() function to convert the string to an integer.

3. Handle any potential ValueError that occurs if the string cannot be converted to an integer.

4. Print or use the integer value in further calculations.

3. Code Program

# Step 1: Initialize a string that represents a number
num_str = '42'

# Step 2: Use the int() function to convert the string to an integer
num_int = int(num_str)

# Step 3: Print the resulting integer
print(num_int)

# Handling a case where the conversion might fail
try:
    # Trying to convert a non-numeric string will raise a ValueError
    invalid_num_str = 'Python'
    invalid_num_int = int(invalid_num_str)
except ValueError as e:
    print(f"Error: {e}")

Output:

42
Error: invalid literal for int() with base 10: 'Python'

Explanation:

1. num_str is a string initialized with '42', which is a numeric literal in string form.

2. num_int is the variable that stores the integer value after conversion using the int() function.

3. When the print() function is called, it outputs 42, the integer equivalent of the string '42'.

4. In the second part of the code, the string 'Python' is used to demonstrate error handling. Since 'Python' is not a numeric string, int() raises a ValueError, which is then caught in the except block and a corresponding error message is printed.


Comments