Wednesday, January 15, 2025
HomeTechConvert String to Int in Python

Convert String to Int in Python

Python provides a built-in function, int(), to convert a string representation of a number into an integer.

Syntax

python
int(string, base)
  • string: The string to be converted.
  • base (optional): The numerical base of the input string (e.g., binary, octal, decimal, hexadecimal). The default is 10.

Examples

1. Basic Conversion

python
num_str = "123"
num = int(num_str)
print(num) # Output: 123
print(type(num)) # Output: <class 'int'>

2. Converting Strings with Different Bases

  • Binary (Base 2):
python
binary_str = "1101"
num = int(binary_str, 2)
print(num) # Output: 13
  • Hexadecimal (Base 16):
python
hex_str = "1A"
num = int(hex_str, 16)
print(num) # Output: 26

3. Handling Strings with Leading Whitespace

The int() function ignores leading and trailing whitespace.

python
num_str = " 456 "
num = int(num_str)
print(num) # Output: 456

4. Converting a String with a Floating Point

Attempting to convert a string containing a floating-point number directly to an integer will raise an error. Convert it to a float first if needed.

python
num_str = "123.45"

# Incorrect: Raises ValueError
# num = int(num_str)

# Correct
num = int(float(num_str))
print(num) # Output: 123

5. Error Handling

If the string cannot be converted into an integer, a ValueError is raised.

python
try:
num = int("abc") # Invalid string
except ValueError:
print("Invalid input, cannot convert to integer.")

Output:

css
Invalid input, cannot convert to integer.

Important Notes

  1. Input Validation: Always validate the string before converting, especially when taking user input.
  2. Performance: The int() function is optimized and works efficiently even with large numbers.

Using the int() function ensures a reliable and straightforward way to convert strings to integers in Python.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x