[英]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: @AShelly的答案是理想的解决方案,但是如果您希望使用循环,则可以使用以下方法:
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'
. print的命名参数(
end = ' '
)意味着print
语句将以' '
而不是通常的'\\n'
结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.