简体   繁体   中英

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.

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:-

"abc"
"bvc"
"mnb"

How can i get the output in the same line like this?

"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.

Using

print(*my_dict.keys())

will unpack the keys into an argument list for print and product output

abc bvc mnb

If you need commas in the output, you can add the sep=", " keyword:

print(*my_dict.keys(),sep=", ")

You can a make a 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(key,end=", ")

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