[英]To add a new line before a set of characters in a line using python
我有一系列巨大的字符,其中一組字符不斷重復。 該行是: qwethisistheimportantpartqwethisisthesecondimportantpart
字符串中沒有空格。 我想在字符串'qwe'之前添加一個新行,以便我可以區分每個重要部分。
輸出:
qwethisistheimportantpart
qwethisisthesecondimportantpart
我試過用
for line in infile:
if line.startswith("qwe"):
line="\n" + line
它似乎不起作用
str.replace()
可以做你想要的:
line = 'qwethisistheimportantpartqwethisisthesecondimportantpart'
line = line.replace('qwe', '\nqwe')
print(line)
您可以使用re.split()
然后使用\\nqwe
加入:
import re
s = "qwethisistheimportantpartqwethisisthesecondimportantpart"
print '\nqwe'.join(re.split('qwe', s))
輸出:
qwethisistheimportantpart
qwethisisthesecondimportantpart
我希望這能幫到您
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.