在 Python 中用新行替换空格

pHo*_*pec 4 python replace

我试图用 '\n' 替换 '\s',但是当我打印时line2,它不会打印一行用新行替换空格的行。有人能指出我的语法有什么问题吗?

for line in fi:
    if searchString in line:
        line2 = line.replace('\s' , '\n') 
        print line2
Run Code Online (Sandbox Code Playgroud)

hee*_*ayl 7

\s是一个正则表达式令牌,不会被str.replace.

做:

line.replace(' ', '\n') 
Run Code Online (Sandbox Code Playgroud)


the*_*orn 5

.replace()替换字符串,你想要re.sub(..),例如:

for line in fi:
    if searchString in line:
        line2 = re.sub(r'\s' , '\n', line) 
        print line2
Run Code Online (Sandbox Code Playgroud)

该文档有更多详细信息:https : //docs.python.org/2/library/re.html#re.sub