Basic Python Issue / removing whitespace

Question:

I am struggling in a python undergraduate class that should have had fewer modules: for a grade, I have a code that reads a formatted file and "prints" a table. The problem is, the last entry of the table has a trailing space at the end. My print statement is

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

I really have no idea what to do here: i have a list that contains something like "11:30", "10:30", "9:00", and it should be printed as 11:30 10:30 9:00 (with no space after the 9:00). I have tried to join my list, but really, most of the concepts I need to do all of this were never even communicated or taught in the class. I guess that’s how it goes, but I’m struggling. My approach is to appropriate existing code, try to understand it, and learn that way, but it’s not making any sense to me.

I am taking Java I at the same time, and Java makes sense to me because the pace of the Java course is about 1/2 of the pace of the Python class: 2x the modules means 1/2 the time. If anyone can help, thank you.

Here’s what I have (I’ll remove the notes if it’s not helpful?)

# 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()
Asked By: DAD9000

||

Answers:

Instead of multiple calls to print, create a single space-delimited string with ' '.join and print that.

print(' '.join(movieTiming[m]))

As you’ve noted, printing a space between list elements is different from printing a space after each element. While you can play around with list indices to figure out which element is the last element and avoid printing a space after it, the join method already handles the corner cases for you.


Similar to what you tried, though, consider an approach not of printing a space after all but the last element, but printing a space before all but the first.

print(movieTiming[m][0], end='')
for t in movieTiming[m][1:]:
    print(f' {t}', end=''
print()

I mention this not because you should consider it an alternative to str.join, but because it helps to think about your problem in different ways.

Answered By: chepner

This might help:

my_list = ['11:00', '12:30', '13:00']

joined = ' '.join(my_list)

print(joined)
# 11:00 12:30 13:00
Answered By: Adrian Kurzeja

Supposed you have:

time = ["19:30","19:00","18:00"]

then you could apply the list as separate arguments:

print(*time)

You can, as always, control the separator by setting the sep keyword argument:

print(*time, sep=', ')

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in time])
print(joined_string)
Answered By: str1ng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.