简体   繁体   English

python regex replace返回一个额外的\\ n

[英]python regex replace returns an extra \n

I am trying to replace some text in a file with python 2.6 我正在尝试用python 2.6替换文件中的一些文本

However, it returns an extra newline here is my code: 但是,它返回一个额外的换行符,这是我的代码:

for line in fileinput.input('/etc/php5/apache2/php.ini', inplace=True):
   replace = re.sub(r'(post_max_size =).[0-9]+(M)', r'\1 64\2', line)
   print replace

Input: 输入:

post_max_size = 6M
sdfsdfsd
post_max_size = 4M
sdfsdf
post_max_size = 164M
dfsdfsdfsdfsdf

output: 输出:

post_max_size = 64M

sdfsdfsd

post_max_size = 64M

sdfsdf

post_max_size = 64M

dfsdfsdfsdfsdf

The extra output you are seing is from print , if you write the file back out, you should not see the extra line breaks. 您要获取的额外输出来自print ,如果将文件写回,则不应看到多余的换行符。

Try it with this: print replace, 尝试以下操作: print replace,

This is a minor point, but you should also pick a different name, as replace is the name for a method in the standard library for strings. 这只是次要点,但是您还应该选择一个不同的名称,因为replace是字符串标准库中方法的名称。

your regex is fine. 您的正则表达式很好。 print adds newline. print添加换行符。 use write instead. 使用write代替。

Try: print replace, instead. 尝试: print replace, The trailing comma suppresses the newline (but adds a trailing space). 尾部逗号禁止换行符(但增加了尾部空格)。 For complete control use the print function from __future__ instead. 为了完全控制,请使用__future__的打印功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM