Search code examples
pythonlistfor-loopf-string

Constructing an f-string by for-looping through a list


I'd like to know how to go from this:

mylist = [10, 20, 30]

to this:

'Quantity 10, quantity 20 quantity 30'

I know it can be done with:

mystring = f"Quantity {mylist[0]}, quantity {mylist[1]} quantity {mylist[2]}"

but isn't there a way to incorporate a for-loop when constructing the f-string instead of having to provide all the list indexes one by one?

Edit: Quantity, quantity, and quantity just happen to be the same string, but they could be anything like 'Quantity 10, rank 20 kingdom and sovrenity 30'. So, there would be different text between the numbers.


Solution

  • You can use list comprehension

    ", ".join([f"Quantity {x}" for x in mylist])
    

    And if you care about the capitalisation....

    f"Quantity {mylist[0]}, " + ", ".join([f"quantity {x}" for x in mylist[1:]])
    

    EDIT: If the words are going to be different you need to zip them for the comprehension

    words=["word1", "word2", "word3"]
    numbers=[10,20,30]
    
    ', '.join([str(word) + " " + str(number) for word,number in zip(words,numbers)]).capitalize()