You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python循环迭代的每个语句末尾打印句号?

How to Add a Period at the End of Each Output Line in This Python Loop?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:12:52