Search code examples
pythonpandasdataframef-string

How to format f-strings from dataframe with curly brackets in the dataframe?


How to format f-strings from dataframe with curly brackets in the dataframe?

Text in a dataframe that has curly brackets { and } in the text, which is intended to trigger f-string formatting of defined variables in the Python code. But the code instead just yields the actual text like "{From}" instead of the actual name. Below is the code. Thank you for your help.

        DocText = DT.loc[(DT['To'] == NameList2) & (DT['From'] == NameList1) & (DT['Type'] == 'Document'), 'Text'].reset_index(drop=True)
        for i in DocText:
                    docap(style='ListNumber1').add_run(f'{i}')

Solution

  • f-strings only work for constant strings, like the f'{i}' you have above. If you're reading strings from an I/O source, you can use the string .format() method to do the substitution.

    string = "checking {From} and {To}"
    print( string.format( From=123, To=456) )
    

    Output:

    checking 123 and 456
    

    Looking further, it looks like you may be expecting the "{From}" string to be substituted with the value of the "From" column. That doesn't work. You might be able to simulate that using .apply, but we'd need to see more details about what data you have and what you are expecting.