Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
+ "]")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading