Home > database >  Is there an easier way to display an array of numbers in a specific base in python?
Is there an easier way to display an array of numbers in a specific base in python?

Time:11-30

To print an array of numbers in a specific base, I've used the following:

print( str(
    [ '{:02x}'.format(array[i])
      for i in range(0, len(array))
    ]
).replace("'", "") ) )

Which converts the array of numbers to an array of string representations of the numbers in the base (in this case hex values of 2 digits), and then converts that array into a string and removes the single quotes.

I guess I could also make a function that generates the output in that or some other way. Perhaps like:

def numbers_as_base(array, base, digits, leading_zeros):
  s = '['
  if len(array) > 0:
    fmt = f'{{:{0 if leading_zeros else ""}{digits}{base}}}'
    for i in range(0, len(array)-1):
      s  = fmt.format(array[i])   ', '
    s  = fmt.format(array[-1])
  return s   ']'

I was just wondering, is there something in the language/standard library that was already available that would do this for me? Also, is there a more efficient way of doing this?

CodePudding user response:

The main thing you need is .join:

array = [31, 14, 41, 15, 59]

print("["   ", ".join([
    '{:02x}'.format(x)
    for x in array])
  "]")

Output:

[1f, 0e, 29, 0f, 3b]

You can also leave out the [] from the list comprehension in this case, creating a generator expression:

print("["   ", ".join(
    '{:02x}'.format(x)
    for x in array)
  "]")
  • Related