首页 > 解决方案 > Replace() 方法在函数中不起作用

问题描述

我正在制作一个接受纯文本文件的函数,然后返回该文件中的单词列表。显然,我想去掉任何换行符 '\n',但是,当使用 '.replace()' 时什么也没有发生。

功能:

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)

示例文本:

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

我的输出:

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

为什么 '.replace()' 方法不起作用?

标签: pythonpython-3.x

解决方案


这可能是 python 或其他一些编程语言将换行读取为 '\n' 转义字符的情况。因此,当 python 读取您的文件时,'\n' 表示新行,'\\n' 表示您在文本文件中写入的实际 '\n' 字符。

所以你需要更换像 a = message.replace('\\n', '')


推荐阅读