Search code examples
string-formattingpython-3.7python-docxargument-unpacking

Unpacking set in string format in python only returns first value


I have converted a DataFrame Column into a set, and I am trying to format the values into a string using the * to unpack it like a list. However, it only returns the first value.

I am using the python-docx to automatically create reports based on the data.

This code selects a column of a DataFrame, drops blank values and converts it into a set. The idea is to eliminate duplicates. The next step uses the format function to enter the set into a string or the report:

set_unique_statgroup = set(self.internal_df.StatGroup.dropna())

self.document.add_paragraph("{} categories have been found, and they are: {}".format(len(set_unique_statgroup), *set_unique_statgroup)

The code returns the following sentence:

"12 categories have been found, and they are: Temperature"

I was hoping it would display all of the items in the set:

"12 categories have been found, and they are: Temperature, Mood, Time of Day (...)"


Solution

  • I have found a workaround, possibly not the most pythonic:

    Use a loop and the add_run function to add to the paragraph for each item in the set:

    for item in set_unique_statgroup:
        p.add_run("{}".format(item))
    
    p.add_run(".")
    

    If anybody has a more compact/pythonic way of doing it, please feel free to post.