简体   繁体   中英

Python: How do I write a message to items in a list without printing each message individually?

In Python3, I'd like to write a blanket message that goes to all items in the list (names of dinner guests, in this case) without having to print each message individually.

For example, if the list is:

guest_list = ['John', 'Joe', 'Jack'] 

I want it to print this line below using each person's name without having to individually print the message 3 times:

print("Hello, " + *name of guest from the list above here* + "! We have found a bigger table!")

Desired Result:

Hello, John! We have found a bigger table! 
Hello, Joe! We have found a bigger table! 
Hello, Jack! We have found a bigger table! 

Is this possible? If so, how? Thanks to any help offered!

If you want to do only one print :

guest_list = ['John', 'Joe', 'Jack']
result_str = ['Hello {}! We have found a bigger table!'.format(guest) for guest in guest_list]
print(result_str.join('\n'))

You can use a simple for loop:

guest_list = ['John', 'Joe', 'Jack']
for x in guest_list:
    print("Hello, " + x + "! We have found a bigger table!")

Hello, John! We have found a bigger table!

Hello, Joe! We have found a bigger table!

Hello, Jack! We have found a bigger table!

you can do the following:

for x in guest_list:
    print("Hello, %s! We have found a bigger table!" %x)

Where %s allows you to insert a string format which is replaced by the variable I am passing to it.

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