To add a new line before a character set in a line using python

I have a string of huge characters repeating a character set. Line:qwethisistheimportantpartqwethisisthesecondimportantpart

There are no spaces in the line. I want to add a new line before the qwe line so that I can distinguish each important part from the other.

Output:

qwethisistheimportantpart
qwethisisthesecondimportantpart

I tried to use

for line in infile:
    if line.startswith("qwe"):
        line="\n" + line

and doesn't seem to work

+4
source share
3 answers

str.replace() can do what you want:

line = 'qwethisistheimportantpartqwethisisthesecondimportantpart'
line = line.replace('qwe', '\nqwe')
print(line)
+5
source

You can use re.split()and then join \nqwe:

import re

s = "qwethisistheimportantpartqwethisisthesecondimportantpart"

print '\nqwe'.join(re.split('qwe', s))

Conclusion:

qwethisistheimportantpart
qwethisisthesecondimportantpart
+2
source

,

string = 'qwethisistheimportantpartqwethisisthesecondimportantpart'
split_factor = 'qwe'
a , b , c  = map(str,string.split(split_factor))
print split_factor + b
print split_factor + c

Python 2.7   , .

:

qwethisistheimportantpart
qwethisisthesecondimportantpart
+2

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


All Articles