我正在尝试编写一个函数,该函数以文件名作为参数并返回一个字符串,其中所有\n字符均替换为该_字符。
这是我所做的:
def replace_space(filename):
wordfile = open(filename)
text_str = wordfile.read()
wordfile.close()
text_str.replace("\n", "_")
replace_space("words.txt")
Run Code Online (Sandbox Code Playgroud)
我还尝试使用“”代替“ \ n”:
text_str.replace(" ", "_")
Run Code Online (Sandbox Code Playgroud)
Python与Haskell和Scala等语言不同,None如果到达函数体的末尾而没有显式的return语句,Python将返回。因此,您需要这样做:
def replace_space(filename):
with open(filename) as wordfile:
text_str = wordfile.read()
return text_str.replace("\n", "_")
Run Code Online (Sandbox Code Playgroud)
还请注意使用with代替open和close; 即使您在途中遇到异常,也可以确保关闭文件。