0

For example, if I have lots of lines of coding doing something like:

print('{:=+5d}'.format(my_value))

or perhaps something more involved like:

print('{:04d}-{:04d}|{:03d}'.format(val1, val2, val3))

Is there a good way (and is it good practice) to replace the string format conversion specifier with something so that I:

  1. Reduce the number of times that needs to be typed out
  2. Make it more human readable
  3. Make the format string parametric so it can be changed in one place

Edit for more clarity:

  • These prints occur throughout the code and aren't just a single list of items in one spot I can loop through. The formats are also used for strings in log messages and other non-print places.
  • I might want to even specify the string format programmatically
  • This is running on a legacy python 2 script
Otus
  • 305
  • 1
  • 5
  • 16
  • Does this answer your question? [How to format a floating number to fixed width in Python](https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – etch_45 Nov 24 '20 at 07:50
  • It is not good practice. – thebjorn Nov 24 '20 at 08:10
  • Why is it not good practice? Using "magic values" and repeating the same literal is generally bad practice. If I want to change the format at some point I would have to do a global string replace which can be tedious and error prone – Otus Nov 24 '20 at 17:27

2 Answers2

0

Try this:

['{:=+5d}'.format(val) for val in all_vals]
Natheer Alabsi
  • 2,790
  • 4
  • 19
  • 28
  • I've added some more details to the question now, but it's not just one place that formats all the strings. They are scattered throughout the code and used in different ways – Otus Nov 24 '20 at 17:24
0

According to python 8.6, you can write this code like this to be more pythonic using something called f-string¹

Code Syntax

print(f'{val1:04d}-{val2:04d}|{val3:03d}')
Ahmed
  • 796
  • 1
  • 5
  • 16
  • I've added some more details to the question explaining that I'm suck on py2 for this particular script. However, even f-strings used like this don't solve the issue of wanting to modify the string format globally. – Otus Nov 24 '20 at 17:53
  • No, it's just an organizational decision to not update legacy source that's in maintenance mode. However, I'm happy to hear of Py3 solutions I can use in future projects as well – Otus Nov 24 '20 at 20:31