Reputation: 23
Hello I just have a question about int function. It convert data(for example, string) to int data. My question is how this function works like this? I tried to implement int function myself without any help with built-in function,and I realized this is really hard working. I searched about int function, most of sites have simple description. Just saying 'Return an integer object' like this. It looks easy but hard for me...
I searched and didn't found what I want
Upvotes: -5
Views: 94
Reputation: 1
Pythons int() function does more than just converting a string to integer.The behavior varies based on the argument and an optional base parameter. we can break down behavior as follows:
int(5) # return 5
int(2.04) # return 2
int()
strips any whitespace, and also can handle an optional sign(+
or -
) and then converts the sequence of digits to an integer.int(" -10 ") # returns -10
int("1010", 2) # returns 10 (binaray to decimal)
+
or -
).For example:
def custom_integer_converter(s, base=10):
# Ensure input is a string
if not isinstance(s, str):
raise TypeError("Input must be a string")
s = s.strip().lower() # Handle whitespace and case insensitivity
if not s:
raise ValueError("Empty string after stripping whitespace")
# Determine the sign
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
elif s[0] == '+':
s = s[1:]
if not s:
raise ValueError("No digits after sign")
# Validate characters and convert to integer
value = 0
for c in s:
# Convert character to numerical value
if c.isdigit():
digit = ord(c) - ord('0')
else:
digit = ord(c) - ord('a') + 10
# Check if digit is valid for the base
if not (0 <= digit < base):
raise ValueError(f"Invalid character '{c}' for base {base}")
value = value * base + digit
return sign * value
enter image description here The image contains the implementation of the code mentioned above, along with tested inputs.
Upvotes: -4