Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To add a new line before a set of characters in a line using python

Tags:

python

string

I have a line of huge characters in which a set of characters keep repeating. The line is : qwethisistheimportantpartqwethisisthesecondimportantpart

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

Output :

qwethisistheimportantpart
qwethisisthesecondimportantpart

I tried using

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

and it doesn't seem to work

like image 793
Rahul Avatar asked Jul 11 '17 15:07

Rahul


People also ask

How do you add a new line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you insert a new line into a string of text?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you add n to a string in Python?

You can just use n for specifying a newline character, and Python will translate it to the appropriate newline character for that platform.

How do you insert a break in Python?

The new line character in Python is used to mark the end of a line and the beginning of a new line. To create a string containing line breaks, you can use one of the following. Newline code \n(LF), \r\n(CR + LF).


2 Answers

str.replace() can do what you want:

line = 'qwethisistheimportantpartqwethisisthesecondimportantpart'
line = line.replace('qwe', '\nqwe')
print(line)
like image 97
Robᵩ Avatar answered Oct 21 '22 18:10

Robᵩ


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

import re

s = "qwethisistheimportantpartqwethisisthesecondimportantpart"

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

Output:

qwethisistheimportantpart
qwethisisthesecondimportantpart
like image 42
Ajax1234 Avatar answered Oct 21 '22 19:10

Ajax1234