简体   繁体   English

如何从字典将打印循环功能转换为最终字符串

[英]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.

相关问题 如何从循环中打印或返回迭代的最终值? - How to print or return the final value of the iteration from loop? 如何从字典字符串中打印特定键。 - How to print a specific key from a string of dictionaries. 如何在Python中将字典列表的值从字符串转换为浮点数 - How to convert the values of a list of dictionaries from a string to a float in Python 循环用于打印字典字典 - loop for to print a dictionary of dictionaries 将字典列表中的字典值从字符串转换为 integer - Convert value in dictionaries from a list of dictionaries from a string to integer 如何在递归循环中继续附加到 numpy 数组,然后打印出最终结果/将其传递给另一个 function? - How to keep appending to a numpy array inside a recurive loop and then print out the final result/pass it to another function? 如何从字典中获取输入? 并打印所需的值..我想使用输入 function 并打印“zinger burer” - how to take input from dictionaries ? and print that desired value ..i want to use input function and print “zinger burer” 将字典字符串转换为字典列表 - Convert a string of Dictionaries to a list of dictionaries 如何从字典列表中打印字典项目 - How to print dictionary items from list of dictionaries 将字符串转换为字典列表 - Convert a string to list of dictionaries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM