如何在Python循环迭代的每个语句末尾打印句号?
I have a simple Python script that prints out people's favorite places, but I need to add a period at the end of each line.
My Current Code
favorite_places={'john':['serbia','bulgaria','israel'], 'adam':['russia','london','spain'], 'eden':['turkey','california','london']} for name,places in favorite_places.items(): print("\n"+ name.title()+"'s favorite places are:" , end=' ') for place in places: print( place.title()+"",end=' ')
Current Output
John's favorite places are: Serbia Bulgaria Israel
Adam's favorite places are: Russia London Spain
Eden's favorite places are: Turkey California London
Desired Output
John's favorite places are: Serbia Bulgaria Israel.
Adam's favorite places are: Russia London Spain.
Eden's favorite places are: Turkey California London.
Great question! The main issue here is that your two for loops are separate—right now, the second loop doesn't run inside the first one, so you can't easily add the period after each person's list of places. Here are two clean solutions to fix this:
Solution 1: Nested Loops with a Final Period Print
First, we'll nest the place loop inside the name loop, so we handle each person's full entry in one go. After printing all their favorite places, we just add a print statement for the period:
favorite_places = { 'john': ['serbia', 'bulgaria', 'israel'], 'adam': ['russia', 'london', 'spain'], 'eden': ['turkey', 'california', 'london'] } for name, places in favorite_places.items(): # Print the name line without a newline print(f"\n{name.title()}'s favorite places are:", end=' ') # Loop through and print each place for place in places: print(place.title(), end=' ') # Add the period at the end of the line print('.', end='')
Solution 2: Use str.join() for Cleaner Code
A more concise approach is to use Python's str.join() method to combine all the capitalized places into a single string. This lets us print the entire line in one go, including the trailing period:
favorite_places = { 'john': ['serbia', 'bulgaria', 'israel'], 'adam': ['russia', 'london', 'spain'], 'eden': ['turkey', 'california', 'london'] } for name, places in favorite_places.items(): # Capitalize each place and join them with spaces capitalized_places = ' '.join(place.title() for place in places) # Print the full line with the period print(f"\n{name.title()}'s favorite places are: {capitalized_places}.")
Both solutions will give you the exact output you're looking for. The second method is generally preferred because it's more readable and avoids multiple calls to print() for each line.
内容的提问来源于stack exchange,提问作者Slim Shady

