Oliver
Oliver

Reputation: 11

how to convert a print loop function into a final string from dictionaries

How can I make the print loop add together to form a string with spaces?

positions = [1, 2, 3, 4, 1, 2, 5, 6, 7, 2, 8, 6, 3, 9, 10]
words = ['this', 'is', 'not', 'howr', 'needed', 'and', 'it', 'wrong', 'right', ':(']
poswords = dict(zip(positions, words))
print(poswords, words)
for i in positions: 
    print(poswords[i]," ",)

When I simply want the print to be saved in a string

Upvotes: 0

Views: 67

Answers (2)

Nick is tired
Nick is tired

Reputation: 7055

@AShelly's answer is the ideal solution, but if you would prefer to use the loop then you can use the following:

positions = [1, 2, 3, 4, 1, 2, 5, 6, 7, 2, 8, 6, 3, 9, 10]
words = ['this', 'is', 'not', 'howr', 'needed', 'and', 'it', 'wrong', 'right', ':(']
for i in positions: 
    print(words[i-1], end = ' ')

The named parameter of print (end = ' ') means that the print statement will end with a ' ' rather than the usual '\n'.

Upvotes: 0

AShelly
AShelly

Reputation: 35520

sentence =  " ".join([words[i-1] for i in positions]) #?

yields:

'this is not howr this is needed and it is wrong and not right :('

Upvotes: 1

Related Questions