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]}, quantit
Solution 1:
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 inzip(words,numbers)]).capitalize()
Post a Comment for "Constructing An F-string By For-looping Through A List"