pythonstringvariable-assignment

Adding fragments to multiple strings simultaneously in Python


I have a script that is creating a report text file. There are a lot of fragments where I add text to my string variable like this:

report_text += f'Bla bla {value} bla\n'
...
report_text += f'Bla2 bla2 {value2} bla2\n'
...
report_text += f'Bla3 bla3 {value3} bla3\n'

And in the end I export this long string as a text file with all the collected information as a report (or log).

But now I need to add some of the lines to another string variable to be able to export it in some other report file which should contain only some subset of the lines of report_text.

So what I need is to add new assignments to some of the existing statements like this:

report_text, report_text_2 += f'Bla bla {value} bla\n'
...
report_text += f'Bla2 bla2 {value2} bla2\n'
...
report_text, report_text_2 += f'Bla3 bla3 {value3} bla3\n'

(This code will not work of course, but I wish it did)

Is there any easy way in Python to add this second variable in existing statements without repeating them?

I know I can use logging lib and I can make two different log containers or something like that. But I'm sure there is some easy way of doing it by just two different strings. Or not?


Solution

  • I'd suggest making report_text to a list, to avoid recreating new strings everytime you do +=

    If you insist on doing it the string way with minimal modification to your existing code, then you can use Assignment expressions

    Something like:

    # Before
    report_text += f'Bla bla {value} bla\n'
    
    # After
    report_text += (x := f'Bla bla {value} bla\n')
    report_text2 += x
    

    I'd still recommend having variable x in a separate line.