简体   繁体   中英

Printing object attributes on one line

I've got a list called "location" with two class-created objects inside:

location = [rat1,rat2]

I'd like to print an attribute of both rats on one line, while keeping the location list dynamic. I have this currently:

for i in range(0,len(location)):
    print((location[i].vname),sep=',')

This iterates through the lists items, and prints the "vname" attribute for every object in the list it sees. Unfortunately this currently returns:

Young Rat
Adult Rat

If I change sep to end, it prints this:

Young Rat,Adult Rat,

It's almost as if the sep isn't even registered at all in the print. Does anyone have any ideas? Also, sorry for any formatting issues, this is my first time posting on stack exchange.

You should make one call to print and join the various attributes using str.join . The following should work:

print(','.join(rat.vname for rat in location))

Try print ','.join(location) or print ','.join(map(str, location))

More generally, don't iterate using an integer variable in python.

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