简体   繁体   English

如何在 python 中添加 for 循环 inside.join()

[英]How to add a for loop inside .join() in python

I have found people doing something similar to this one in codewars.我发现有人在代码战中做类似的事情。 But for me somehow it never works.但对我来说,它永远不会起作用。 Can someone please tell me what is wrong in this code and what I should do to correct it.有人可以告诉我这段代码有什么问题以及我应该做些什么来纠正它。 Thank you in advance!先感谢您!

PS:I know that writing a for loop outside solves this but I want my code to be neat and concise:D Edit: Thank you guys. PS:我知道在外面写一个 for 循环可以解决这个问题,但我希望我的代码简洁明了:D 编辑:谢谢你们。 It worked!有效!

names = ["Alexa","Siri","Cortana"]
print(" ".join("Hello there ",(i for i in names)))

Here is the fixed code:这是固定代码:

names = ["Alexa","Siri","Cortana"]
print("".join([f"Hello there {i}!\n" for i in names]))

Try this:-尝试这个:-

names = ["Alexa","Siri","Cortana"]

print(', '.join(['Hello there ' + i for i in names]))

Output: - Output:-

'Hello there Alexa,  Hello there Siri,  Hello there Cortana'

You need to format the value into the string which is being joined:您需要将值格式化为正在连接的字符串:

names = ["Alexa","Siri","Cortana"]
print(" ".join(f"Hello there {i}" for i in names))

Output: Output:

Hello there Alexa Hello there Siri Hello there Cortana

First, this is not a for loop, this is a generator expression (in your case) or list/dict/set comprehension.首先,这不是一个 for 循环,这是一个生成器表达式(在你的情况下)或 list/dict/set 理解。 Second, str.join takes only one argument and you provided two - did you want your output to be: Hello there Alexa Hello there Siri Hello there Cortana or Hello there Alexa Siri Cortana ?其次, str.join只接受一个参数,而您提供了两个参数 - 您是否希望您的 output 成为: Hello there Alexa Hello there Siri Hello there CortanaHello there Alexa Siri Cortana Depending on the answer, the code could be:根据答案,代码可能是:

print(" ".join("Hello there " + x for x in names))

or或者

print("Hello there " + " ".join(names))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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