Search code examples
python-3.xconcatenation

Trouble concatenating floats and strings in Python


I'm using this code:

for each in x: 
            descrVar = descrVar + " " + df.iloc[counter,each]

to iterate through a table and concatenate cells into a variable. The problem is, some of the cells will be a Nan. As a result, I'm getting the following error:

TypeError: can only concatenate str (not "numpy.float64") to str

I assume this means a Nan is a float64 and not a str. Is there any way around this, such as forcing every cell to convert to a str?


Solution

  • An f-string will format your data as str.

    for each in x:
        descrVar += f" {df.iloc[counter,each]}"