[英]Replace Space with New Line in Python
I'm trying to replace '\\s' with '\\n', but when I print line2
, it doesn't print a line with the spaces replaced with new lines. 我正在尝试用'\\ n'替换'\\ s',但是当我打印
line2
,它不会打印一行,并用新行替换空格。 Could anybody indicate what's wrong with my syntax? 有人能说出我的语法有什么问题吗?
for line in fi:
if searchString in line:
line2 = line.replace('\s' , '\n')
print line2
.replace()
replaces strings, you want re.sub(..)
, eg: .replace()
替换字符串,你想要re.sub(..)
,例如:
for line in fi:
if searchString in line:
line2 = re.sub(r'\s' , '\n', line)
print line2
The documentation has more details: https://docs.python.org/2/library/re.html#re.sub 该文档包含更多详细信息: https : //docs.python.org/2/library/re.html#re.sub
\\s
is a Regex token, won't be understood by str.replace
. \\s
是一个正则表达式令牌, str.replace
不会理解。
Do: 做:
line.replace(' ', '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.