Aashish sharma Sharma
Aashish sharma Sharma

Reputation: 307

Formatting string in python

I want to write to a file in tabular format and following is code I have written till now.

file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:12}".format("Check"))
file_out.write("{0:12}".format("_5"))
file_out.close()

Testing_string looks like this.

TUPLE        LOGFILE STATUS       FSDB STATUS                   
Check       _5    

Problem is I want _5 to be with check. Please see that I cannot concatenate check with _5 as check is printed first in file then depeding on some logic I fill LOGFILE STATUS FSDB STATUS. If I am unable to fill status then I check if I have to append _5 or not. so due to this I cannot concatenate string. How to then print _5 right next to Check?

Upvotes: 1

Views: 229

Answers (2)

vahndi
vahndi

Reputation: 1045

The problem is that you are specifying 12 characters for Check. Try this:

file_out=open("testing_string","w")
file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
file_out.write("{0:5}".format("Check"))
file_out.write("{0:7}".format("_5"))
file_out.close()

Upvotes: 1

SethMMorton
SethMMorton

Reputation: 48885

In a perfect world, you wouldn't do what is given in the below answer. It is hacky and error-prone and really weird. In a perfect world you would figure out how to write out what you want before you actually write to disk. I assume the only reason you are even considering this is that you are maintaining some old and crusty legacy code and cannot do things "the right way".


This is not the most elegant answer, but you can use the backspace character to overwrite something previously written.

with open('test.txt', 'w') as file_out:
    file_out.write("{0:<12} {1:<20} {2:<30}\n".format("TUPLE","LOGFILE STATUS","FSDB STATUS"))
    file_out.write("{0:12}".format("Check"))
    backup_amount = 12 - len("Check")
    file_out.write("\b" * backup_amount)
    file_out.write("{0:12}".format("_5"))

Output:

TUPLE        LOGFILE STATUS       FSDB STATUS                   
Check_5 

This only works in this specific case because we are completely overwriting the previously written characters with new characters - the backspace nearly backs up the cursor but does not actually overwrite the previously written data. Observe:

with open('test.txt', 'w') as f:
    f.write('hello')
    f.write('\b\b')
    f.write('p')

Output:

helpo

Since we backspaced two characters but only wrote one, the original second character still exists. You would have to manually write ' ' characters to overwrite these.

Because of this caveat, you will probably have to start messing with the length of the format codes (i.e. '{0:12}' might need to become '{0:5}' or something else) when you add '_5'. It's going to become messy.

Upvotes: 2

Related Questions