Convert integer to string in Python - Stack Overflow
python - Convert String to Int without int() - Stack Overflow
Converting decimal strings to int
Convert float to string without losing precision.
Videos
Refer to a basic atoi in C:
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
Which translates into the Python:
def atoi(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
Test it:
>>> atoi('123456789')
123456789
If you want to accommodate an optional sign and whitespace the way that int does:
def atoi(s):
rtr, sign=0, 1
s=s.strip()
if s[0] in '+-':
sc, s=s[0], s[1:]
if sc=='-':
sign=-1
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return sign*rtr
Now add exceptions and you are there!
This is really inefficient but:
>>> zero = ord("0")
>>> s = "1234"
>>> sum([x * 10**i for i, x in enumerate(map(lambda x: x - zero, map(ord, s))[::-1])])
1234
This is slightly better:
>>>> sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
1234
>>> atoi = lambda s: sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
>>> atoi("1234")
1234
I'm trying to switch from pandas to polars and trying to be better about data types. If I try to cast int('3.4') it fails but I can execute int(float('3.4')). Is there a way to change this behavior so that the int casting performs the full conversion?
I'm primarily asking because polars is giving a read error in read_csv. I have created a data map dict with data types and column names but sometimes other people open and write the csv files in excel or something and 279 becomes 279.0 which polars refuses to read in as an int. Is there a way to force it to be an int?