简体   繁体   中英

Beginner Python - Printing Values in a List

I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.

    Objects=["Calculator", "Pencil", "Eraser"]
    print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])

Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?

Thanks

You could use join() here:

Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))

This prints:

Hello Calculator, Pencil, Eraser

You can use the string join function, which will take a list and join all the elements up with a specified separator:

", ".join(['a', 'b', 'c']) # gives "a, b, c"

You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):

Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")

Not sure this is the most elegant way but it works:

strTemp = ""
for i in range(len(Objects)):
    strTemp += Objects[i] + " "
print ("Hello " + strTemp)

Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.

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