How to convert Python2 string with formatting into the new f string used in python3

28 views Asked by At

I am working on converting some Python 2.7 code to reflect a more Python 3.10 method and came across this scenario. A string variable is holding the formatting and then later on variables are added to that string. Not sure how to go about getting rid of the % method and using a f string instead or if that is even necessary.

Here are the two variables.

temp1 = '%-5s %-12s%3s %-10s %-20s %-8s%-18s%-4s %-4s %-46s %-16s\n'
header = temp1 % ('ID','SerialNumber','Cabinet','Type','Last Update','Status','Result','Fail','Pass','Instructions','Resolution')

Output for header is:

ID SerialNumberCabinet Type Last Update Status Result Fail Pass Instructions Resolution

I am wanting to get rid of the % in header and use an f string instead or write this better in Python 3.x if possible.

1

There are 1 answers

1
Milos Stojanovic On BEST ANSWER

Maybe something like this:

temp1 = '{:<5} {:<12} {:>3} {:<10} {:<20} {:<8} {:<18} {:>4} {:>4} {:<46} {:<16}\n'
header = temp1.format('ID','SerialNumber','Cabinet','Type','Last Update','Status','Result','Fail','Pass','Instructions','Resolution')

Or using one-liner:

header = f'{"ID":<5s} {"SerialNumber":<12s}{"Cabinet":>3s} {"Type":<10s} {"Last Update":<20s} {"Status":<8s}{"Result":<18s}{"Fail":<4s} {"Pass":<4s} {"Instructions":<46s} {"Resolution":<16s}\n'