Python provides a built-in function, int()
, to convert a string representation of a number into an integer.
Syntax
string
: The string to be converted.base
(optional): The numerical base of the input string (e.g., binary, octal, decimal, hexadecimal). The default is10
.
Examples
1. Basic Conversion
2. Converting Strings with Different Bases
- Binary (Base 2):
- Hexadecimal (Base 16):
3. Handling Strings with Leading Whitespace
The int()
function ignores leading and trailing whitespace.
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.
5. Error Handling
If the string cannot be converted into an integer, a ValueError
is raised.
Output:
Important Notes
- Input Validation: Always validate the string before converting, especially when taking user input.
- 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.