Search code examples
pythonpython-3.xstring-formatting

Formatting whitespace with tabs


Odd question here. I'm working with some pre-defined output that tab-separates, but with varying tab sizes. So, for example, data look like this:

a:    b,c
qes:  d,e

Except with the \t character instead of spaces between the colon and the characters. I am trying to reproduce this type of output with the python format command to work with the legacy code, but only seem to be able to get it working when using spaces rather than the \t character as my fill. Here is a sketch of my format command:

'{:>8}:{:>5},{:}'.format(foo, bar, do)

Again, I've tried to set \t as my fill character, but it treats it as one character, and just puts in the same amount of tabs as it would spaces - which is not helpful.


Solution

  • So, I think there are two parts to this: how are tabs displayed in your target system, and how do you get the right amount of space in your format string.

    As Bardi Harborow commented, a common convention for displaying tabs is '8 spaces per tab', which means that one tab character can replace up to 8 characters worth of text. However, this is often configurable on a per-program basis. If I just use a single tab in your format string, on a system with 8-space tabs, such as running the script from my Windows command line, it looks like this:

    s:      b,c
    longer: b,c
    

    but with 4-space tabs, it looks like this:

    s:  b,c
    longer: b,c
    

    So, the easiest answer for your problem, under the assumption that none of your foo characters are longer than one tab, you can just use the format string: '{}:\t{},{}'.

    Do you have any more info on what the system you are running the script on? That might help steer the conversation in a more useful direction.

    I understand that you are doing this for legacy reasons, but as a side note, this whole 'tabs can be displayed differently on different machines' is one of the reasons that people use space-justified formatting.