简体   繁体   中英

How to get rid of the last whitespace when printing with end=" "?

Task: Create a solution that accepts an input identifying the name of a text file, for example, "WordTextFile1.txt". Each text file contains three rows with one word per row. Using the open() function and write() and read() methods, interact with the input text file to write a new sentence string composed of the three existing words to the end of the file contents on a new line. Output the new file contents.

The solution output should be in the format cat chases dog cat chases dog

the "WordTextFile1.txt" has only 3 words each in a different row cat chases dog

This is what I have which works however the last line with the sentence has an extra whitespace which is breaking my program. What can I do to get rid of the whitespace and fix my code? help!

file = input()
with open(file, "r+") as f:
    list_words = f.readlines()

for word in list_words:
    print(word.strip())
for word in list_words:
    print(word.strip(), end = " ")    

this is current output:
student
reads
book
student reads book(extra whitespace)

You are properly removing the last white space by word.strip() but adding end = " " just adds the last whitespace again. Change it to:

file = input()
with open(file, "r+") as f:
    list_words = f.readlines()
# I don't see any reason having this for loop
# for word in list_words:
#   print(word.strip())
print(' '.join(word.strip() for word in list_words) # this should work

Edit: Removed the list as it was not required. Thanks to @PranavHosangadi

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