简体   繁体   中英

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

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

yields:

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

@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' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM