0

I have large f-string, and I am braking it (see below), for code readability. but when I print (print to file, it is String.IO object) the string I get the indentation leading each new line (except the first), and I don't want that (my IDE is vscode). When taking the same f-string below, to the python shell interpreter (REPL), the output string is proper.

def foo():
    ml.append(f"""
    #define {ip}_{mtype}_{secname}_{fieldname}_MASK (MASK({H},{L}))
    #define {ip}_{mtype}_{secname}_{fieldname}_START_BIT ({fieldsb})\n""")

the output file looks like:

#define QM_MEM_CBTIRDY_LENGTH (0x40)                           //good line
        #define QM_MEM_CBTIRDY_DATA_MASK (GENMASK(31,0))       //bad line (with indentation)
        #define QM_MEM_CBTIRDY_DATA_START_BIT (0)

I have fix it by removing the indentation between each new line (but its ugly cos the strings with the same function def indentation level, and this is ugly)

def foo():
    ml.append(f"""
#define {ip}_{mtype}_{secname}_{fieldname}_MASK (MASK({H},{L}))
define {ip}_{mtype}_{secname}_{fieldname}_START_BIT ({fieldsb})\n""")

how can i get rid of these indentation characters in the final string ?

Adam
  • 2,820
  • 1
  • 13
  • 33

1 Answers1

1

Triple-quoted (multiline) strings are supposed to preserve the formatting, so that's why you're getting those identations.

You can use concatenation instead:

ml.append(f"#define {ip}_{mtype}_{secname}_{fieldname}_MASK (MASK({H},{L}))\n"
          f"#define {ip}_{mtype}_{secname}_{fieldname}_START_BIT ({fieldsb})\n")

or if you still prefer multi-line strings, you can trim them in a similar way to docstrings.

tromgy
  • 4,937
  • 3
  • 17
  • 18
  • I don't think we need the + operation here. Python will concatenate strings without the use of +. A related answer can be seen [here](https://stackoverflow.com/a/54950733/3766568). – Safwan Dec 20 '21 at 09:55
  • 1
    @Safwan, you're correct. I've updated the answer. – tromgy Dec 20 '21 at 12:39