How to find the length of a number in python

It's been several years since this question was asked, but I have compiled a benchmark of several methods to calculate the length of an integer.

def libc_size[i]: 
    return libc.snprintf[buf, 100, c_char_p[b'%i'], i] # equivalent to `return snprintf[buf, 100, "%i", i];`

def str_size[i]:
    return len[str[i]] # Length of `i` as a string

def math_size[i]:
    return 1 + math.floor[math.log10[i]] # 1 + floor of log10 of i

def exp_size[i]:
    return int["{:.5e}".format[i].split["e"][1]] + 1 # e.g. `1e10` -> `10` + 1 -> 11

def mod_size[i]:
    return len["%i" % i] # Uses string modulo instead of str[i]

def fmt_size[i]:
    return len["{0}".format[i]] # Same as above but str.format

[the libc function requires some setup, which I haven't included]

size_exp is thanks to Brian Preslopsky, size_str is thanks to GeekTantra, and size_math is thanks to John La Rooy

Here are the results:

Time for libc size:      1.2204 μs
Time for string size:    309.41 ns
Time for math size:      329.54 ns
Time for exp size:       1.4902 μs
Time for mod size:       249.36 ns
Time for fmt size:       336.63 ns
In order of speed [fastest first]:
+ mod_size [1.000000x]
+ str_size [1.240835x]
+ math_size [1.321577x]
+ fmt_size [1.350007x]
+ libc_size [4.894290x]
+ exp_size [5.976219x]

[Disclaimer: the function is run on inputs 1 to 1,000,000]

Here are the results for sys.maxsize - 100000 to sys.maxsize:

Time for libc size:      1.4686 μs
Time for string size:    395.76 ns
Time for math size:      485.94 ns
Time for exp size:       1.6826 μs
Time for mod size:       364.25 ns
Time for fmt size:       453.06 ns
In order of speed [fastest first]:
+ mod_size [1.000000x]
+ str_size [1.086498x]
+ fmt_size [1.243817x]
+ math_size [1.334066x]
+ libc_size [4.031780x]
+ exp_size [4.619188x]

As you can see, mod_size [len["%i" % i]] is the fastest, slightly faster than using str[i] and significantly faster than others.

Get the length of an Integer in Python #

To get the length of an integer in Python:

  1. Use the str[] class to convert the integer to a string, e.g. result = str[my_int].
  2. Pass the string to the len[] function, e.g. len[my_str].
  3. The len[] function will return the length of the string.

Copied!

my_int = 1234 my_str = str[my_int] print[len[my_str]] # 👉️ 4

The len[] function returns the length [the number of items] of an object.

The argument the function takes may be a sequence [a string, tuple, list, range or bytes] or a collection [a dictionary, set, or frozen set].

This is why we had to convert the integer to a string - we can't pass an integer to the len[] function as integers are not a sequence or a collection.

If you need to handle a scenario where the number is negative, subtract 1 from the result.

Copied!

my_int = -1234 if my_int

Chủ Đề