python - Replace() 方法在函数内不起作用

标签 python python-3.x

我正在创建一个函数,它接受纯文本文件,然后返回该文件中的单词列表。显然,我想删除任何换行符 '\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()”方法不起作用?

最佳答案

当前文本替换的问题是 \ 被视为转义字符 - 文字字符 \n 被解释为换行符。解决这个问题的方法是通过 \\ 转义 \ 字符本身。更新后的替换语句将显示为:

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

而不是:

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

关于python - Replace() 方法在函数内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55073081/

相关文章:

python - 为什么 super().__init__ 没有自引用?

Python3 : Resize rectangular image to a different kind of rectangle, 保持比例并用黑色填充背景

python - 持久化 urllib.request 连接到 HTTP 服务器

python - 等轴 Bokeh 图

python - 排序列表的反向索引

python - 避免 Python 中的相对导入和 sys.path

python - 使用正则表达式在 python 中验证 ip 地址

python-3.x - 有没有办法在flask-socketio事件中修改flask session ?

python - 如何在 TensorFlow 中选择交叉熵损失?

python - 在 2 个 Python 进程之间共享数据结构