-1

I have a .txt file with some words in it like "example". I also have the following code would be:

Name = open("file.txt", "r")
print(name.read())
print("text")
input()

Why is there a whitespace in the output like

"example

text"

And how do I stop that from happening?

jww
  • 97,681
  • 90
  • 411
  • 885
RepoSepo
  • 1
  • 1
  • 7
    In Python 3, the print function has an optional argument `end`. So you can do `print(name.read(), end=' ')` to not have a new line. The default end is a new line. – brentertainer Jul 26 '19 at 05:49
  • Please show the relevant code, show the relevant data and state the exact problem or error. Also see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – jww Jul 26 '19 at 06:05

3 Answers3

3

The reason why you have got an "extra" whitespace may be that the file "file.txt" ends with extra whitespace. You should check every byte of the file, especially the '\n' and '\r' characters.

To avoid the problem,

print(name.read().rstrip())
print("text")

str.rstrip wipes out extra whitespaces at the end of the string. Although I am not sure what caused your problem, str.rstrip should stop that from happening.

xiao-Tiger
  • 46
  • 1
  • 3
1

Use this link:Python Remove Character from String. It will solve your problem.

Name = open("file.txt", "r")
print(Name.read().replace('\n', ''))
print("text")
input()
akash
  • 779
  • 5
  • 16
0

use can do something like this

ans=''
with open('test.txt','r') as f:
    for line in f:
        for word in line.split():
           ans+=word+' '
print(ans)

separate it word by word and do whatever you want .

itsvinayak
  • 140
  • 1
  • 16