[英]Print output of loop in same line python?
I am new to learning python and a bit confused and hoping i can get some help.我是学习 python 的新手,有点困惑,希望能得到一些帮助。
I have a dict here我在这里有一个字典
my_dict = { "abc":1, "bvc":2, "mnb":3}
I am getting the keys using:-我正在使用以下方法获取密钥:-
keys = my_dict.keys()
for key in keys:
print(key)
and i get the output:-我得到了 output:-
"abc"
"bvc"
"mnb"
How can i get the output in the same line like this?我怎样才能像这样在同一行中获得 output?
"abc", "bvc", "mnb"
I tried using我尝试使用
print(key.join(' ')+',')
in my loop but it doesn't work as expected.在我的循环中,但它没有按预期工作。
Any help will be appreciated.任何帮助将不胜感激。
To avoid printing a new line every time you can use print(key, end="")
or also print(key, end=", ")
and can then make so that it does not write the last comma.为了避免每次都打印新行,您可以使用print(key, end="")
或print(key, end=", ")
然后可以使它不写最后一个逗号。
Using使用
print(*my_dict.keys())
will unpack the keys into an argument list for print
and product output将密钥解压缩到print
和产品 output 的参数列表中
abc bvc mnb
If you need commas in the output, you can add the sep=", "
keyword:如果 output 中需要逗号,可以添加sep=", "
关键字:
print(*my_dict.keys(),sep=", ")
You can a make a string.join
你可以制作一个string.join
print(', '.join(my_dict.keys()))
By default print() method add the new line character, if we want to override this then we need pass the explicitly char..默认情况下 print() 方法添加新行字符,如果我们想覆盖它,那么我们需要传递显式字符..
print(key,end=", ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.