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

Python课程作业问题:移除表格末尾的尾随空格

问题

我正在上一门进度快得离谱的本科Python课,作业要求写代码读取格式化文件并打印成表格。现在的问题是,表格每行最后一个放映时间后面总会多一个尾随空格。我现在用的打印代码是:

for time in movieTiming[m]:
        print(time, end=" ")

我的时间列表大概是["11:30", "10:30", "9:00"],想要的输出是11:30 10:30 9:00(最后一项后面不能有空格)。我试过用join方法,但课上还没教这个,完全搞不懂。另外我还在学Java I,进度只有Python课的一半,理解起来轻松多了。附上完整代码:

# First we open the file named "movies.csv" using the open()

f = open(input())
# f.readlines() reads the contents of the file and stores each line as a separate element in a list named movies.
movies = f.readlines()
# Next we declare 2 dictionaries named movieTiming and movieRating.
# movieTiming will store the timing of each movie.
# The key would be the movie name and the value would be the list of timings of the movie.
movieTiming = {}
# movieRating will store the rating of each movie.
# key would be the movie name and the value would be the rating of the respective movie.
movieRating = {}

# Now we traverse through the movies list to fill our dictionaries.
for m in movies:
    # First we split each line into 3 parts that is, we split the line whenever a comma(",") occurs.
    # split(",") would return a list of splitted words.
    # For example: when we split "16:40,Wonders of the World,G", it returns a list ["16:40","Wonders of the World","G"]
    movieDetails = m.split(",")
    # movieDetails[1] indicates the movie name.
    # So if the movie name is not present in the dictionary then we initialize the value with an empty list.
    #need a for loop 
    if(movieDetails[1] not in movieTiming):
        movieTiming[movieDetails[1]] = []
    # movieDetails[0] indicates the timing of the movie.
    # We append the time to the existing list of the movie.
    movieTiming[movieDetails[1]].append(movieDetails[0])
    
    # movieDetails[2] indicates the rating of the movie.
    # We use strip() since a new line character will be appended at the end of the movie rating.
    # So to remove the new line character at the end we use strip() and we assign the rating to the respective movie.
    movieRating[movieDetails[1]] = movieDetails[2].strip()

# Now we traverse the movieRating dictionary.
for m in movieRating:
    # In -44.44s, negative sign indicates left justification.
    # 44 inidcates the width assigned to movie name.
    # .44 indicates the number of characters allowed for the movie name.
    # s indicates the data type string.
    # print() generally prints a message and prints a new line at the end.
    # So to avoid this and print the movie name, rating and timing in the same line, we use end=" "
    # end is used to print all in the same line separated by a space.
    print("%-44.44s"%m,"|","%5s"%movieRating[m],"|",end=" ")
    # Now we traverse through the movieTiming[m] which indicates the list of timing for the particular movie m.
    
    for time in movieTiming[m]:
        
            
        print(time, end=" ")
    # This print() will print a new line to print the next movie details in the new line.
    print()
解决办法(不用join)

既然课上还没教join,用你已经学过的循环、索引和条件判断就能搞定,和Java里处理类似问题的思路差不多,两种方法选一个就行:

方法一:判断是否是最后一个元素

先拿到时间列表,然后遍历每个元素的索引,当索引是最后一个时,打印时不加空格,其他情况加空格结尾:

# 替换原来的时间循环部分
timings = movieTiming[m]
for i in range(len(timings)):
    if i == len(timings) - 1:
        # 最后一个时间,结尾不加空格
        print(timings[i], end="")
    else:
        print(timings[i], end=" ")

方法二:先打第一个元素,后面的元素前面加空格

先打印第一个时间(不加前缀空格),然后从第二个时间开始,每个前面加空格,这样自然不会有末尾空格:

# 替换原来的时间循环部分
timings = movieTiming[m]
if timings:  # 防止列表为空报错
    print(timings[0], end="")
    for time in timings[1:]:
        print(" " + time, end="")

这两种方法都不需要用到没学过的知识点,应该容易理解。


内容的提问来源于stack exchange,提问作者DAD9000

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:40:25