Python replace with regex

Does anyone know how to replace all ocurences '<\ d +' with a regular expression with '\ r \ n <\ d +', for example

"<20" 

should be converted to

 "\r\n<20" 

but

 "> HELLO < asassdsa" 

do not touch

+4
source share
2 answers
 >>> import re >>> str = "<20" >>> output = re.sub(r'<(?=\d)', r'\r\n<', str) >>> output '\r\n<20' 
+6
source
 import re def replace(value): return re.sub(r'(<\d)', r'\r\n\1', value) 

Or using lookahead:

 import re def replace(value): return re.sub(r'(?=<\d)', r'\r\n', value) 
+3
source

Source: https://habr.com/ru/post/1395397/


All Articles