首页 > 解决方案 > 如何编写一个函数,它接受一个文件名并返回一个字符串,其中所有 \n 字符都替换为“_”

问题描述

我正在尝试编写一个函数,该函数采用文件名并返回一个字符串,其中所有 \n 字符都替换为“_”,但我的代码在 shell 中没有返回任何内容(没有错误),但我不确定我是什么我做错了!我们还没有学会使用'with'操作符,只是for和in。

def replace_space(filename):
    text_str = ''
    wordfile = open(filename)
    text_str = wordfile.read()
    wordfile.close()
    return text_str.replace("\n", "_")

print(replace_space("roses.txt"))

标签: pythonthonny

解决方案


推荐阅读