Search code examples
pythonstringprefix

Add prefixes to word groups in Python


How can I add a prefix to each single word in a given word group using .join function?

:param vocab_words: list of vocabulary words with a prefix.
:return: str of prefix followed by vocabulary words with
prefix applied, separated by ' :: '.

This function takes a `vocab_words` list and returns a string
with the prefix  and the words with prefix applied, separated
 by ' :: '. "

I understand that prefix is always vocab_words[0] in the string.

I tried

 def make_word_groups(vocab_words):
    return ' :: ' .join(vocab_words[0] for i in vocab_words[0:])

It does not work. I am getting AssertionError. As a result - lot of prefixes and only then some words with prefixes.


Solution

  • Try this:

    def make_word_groups(vocab_words):
       separator = ' :: '
    
       prefix = vocab_words[0]
       words = vocab_words[1:]
    
       prefixed_words = [prefix + word for word in words]
       result = prefix + separator + separator.join(prefixed_words)
    
       return result