Home > Back-end >  String formatting using a list
String formatting using a list

Time:12-13

I have a list of keywords from which I want to create a certain query named _KDWS. I have a query suffix prefix and I want to return a string that starts with prefix and is followed by every keyword from _KWDS:

something like this:

    def _generate_query(self, prefix): # TODO
         return f"{prefix} {kwd for kwd in self._KDWS}"

I expect the returned string to look like this:

    "prefix kwd1 kwd2 kwd3 kwd4 kwd5 ... kwdN"

CodePudding user response:

Use str.join

def _generate_query(self, prefix):
    return f"{prefix} {' '.join(self._KDWS)}"

So the f-string isn't very useful now, and something like that could be nice too

def _generate_query(self, prefix):
    return ' '.join([prefix, *self._KDWS])
  • Related