2

I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline '\n', however, when using '.replace()' nothing happens.

Function:

textfile = 'name.txt'

def read_words(filename):
    f = open(filename,'r')
    message = f.read()
    a = message.replace('\n', '')
    wordlist = a.split(' ')
    print(wordlist)

read_words(textfile)

Sample txt:

This\n\nis\n\n\na\n\n\nmy\n\nwfile with spaces and blanks

My output:

['This\\n\\nis\\n\\n\\na\\n\\n\\nmy\\n\\nwfile', 'with', 'spaces', 'and', 'blanks']

Why is the '.replace()' method not working?

17
  • 2
    The replace method is certainly working. What's your expected output? Commented Mar 9, 2019 at 1:25
  • 2
    Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything. Commented Mar 9, 2019 at 1:26
  • 5
    Is sample txt literally the string This\n\nis\n\n\na\n\n\nmy\n\nwfile with spaces and blanks, or are you replacing the newlines with \n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\\n', '') Commented Mar 9, 2019 at 1:28
  • 1
    How does one input the single character '\n' in a txt file? Commented Mar 9, 2019 at 1:29
  • 2
    @DillonDavis Happy to accept an answer of yours if you post one Commented Mar 9, 2019 at 1:45

2 Answers 2

1

The issue with your current text replacement is that \ is considered an escape character- the literal characters \n are interpreted as a newline character instead. To solution to this is to escape the \ character itself, via \\. Your updated replace statement would then read:

a = message.replace('\\n', '')

instead of:

a = message.replace('\n', '')
Sign up to request clarification or add additional context in comments.

Comments

1

This might be case that python or some other programming languages reads new line as '\n' escape character. So when python reads your file '\n' means new line and '\\n' means actual '\n' character you wrote in the text file.

So you need to replace like a = message.replace('\\n', '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.