The int()
function in Python converts a value to an integer.
Key takeaways:
Use Python’s built-in
int()
function to easily convert numeric strings to integers, e.g.,int("123")
.The
int()
function can convert strings representing numbers in various bases, such as binary (int("1010", 2)
) or hexadecimal (int("1F", 16)
).
Converting a string to an integer is a common task in Python programming. Whether we’re processing user input, parsing data, or working on computations, knowing how to handle this operation efficiently is crucial.
int()
functionThe most straightforward way to convert a string to an integer is by using Python’s built-in int()
function.
Note: The function returns
0
if no arguments are passed.
int(x, base=10)
The int()
function takes a string (or any object) representing a number and converts it into an integer. The function performs the conversion without errors if the string contains valid numeric characters.
Here’s a breakdown of the parameters it takes:
x: The value to convert into an integer. It can be:
A number (e.g., float
, bool
)
A string representing an integer (e.g., "42"
)
A string representing a number in a different base (e.g., "1010"
in binary)
base: The base of the number system for conversion.
If x
is a string, base
specifies the number system (e.g., 2
for binary, 16
for hexadecimal, 8
for octal).
If x
is a number (not a string), base
is ignored.
print(int("42")) # Output: 42
Python provides built-in functions to convert strings representing numbers in different bases (binary, octal, hexadecimal) into integers and vice versa.
# Converting a binary string to an integerbinary_str = "1010" # Binary representation of 10binary_num = int(binary_str, 2)print("Binary to Integer:", binary_num)# Converting an octal string to an integeroctal_str = "12" # Octal representation of 10octal_num = int(octal_str, 8)print("Octal to Integer:", octal_num)# Converting a hexadecimal string to an integerhex_str = "A" # Hex representation of 10hex_num = int(hex_str, 16)print("Hexadecimal to Integer:", hex_num)
When converting strings to numbers, invalid inputs (such as non-numeric characters) can cause errors. We can handle such cases using try-except
and isdigit()
method.
try-except
The try
block attempts to convert the string to an integer. If the string contains invalid characters (like letters or decimals), a ValueError
is raised and caught in the except
block. An error message is printed, and None
is returned.
def safe_convert_to_int(s):"""Converts a string to an integer safely using try-except."""try:return int(s) # Attempt conversionexcept ValueError:print(f"Error: '{s}' is not a valid integer.")return None# Test casesinputs = ["123", "42a", "98.6", "-50", "ten"]for input_str in inputs:result = safe_convert_to_int(input_str)print(f"Input: '{input_str}' → Output: {result}")
Learn the basics with our engaging Learn Python course!
Start your coding journey with Learn Python, the perfect course for beginners! Whether exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun. Join now and start your Python journey today—no prior experience is required!
str.isdigit()
isdigit()
checks if the string consists only of digits (0-9
). It does not support negative numbers ("-50"
will fail). If isdigit()
returns True
, the string is converted to an integer. If False
, an error message is printed, and None
is returned.
def safe_convert_with_isdigit(s):"""Converts a numeric string to an integer using isdigit()."""if s.isdigit():return int(s)else:print(f"Error: '{s}' is not a purely numeric string.")return None# Test casesinputs = ["123", "42a", "98.6", "-50", "ten"]for input_str in inputs:result = safe_convert_with_isdigit(input_str)print(f"Input: '{input_str}' → Output: {result}")
The int ()
function in Python makes converting a string to an integer simple and versatile. We can easily handle various scenarios by incorporating techniques such as error handling, stripping whitespace, and validating input.
Haven’t found what you were looking for? Contact Us
Free Resources