-3

How to add "\n" after a certain number of delimiters in python?

For example, the data can be in this form. string = "1|2|Hello people|3 1|4|It can be a sentence too|8"

How to add "\n" after, let's say, 3 delimiters ("|")?

The output should be something like this. "1|2|Hello people|3", "1|4|It can be a sentence too|8"

I know I should use re.split, but I'm not too sure how to do it. Can someone help me please? Thanks in advance!

Jacky Neo
  • 1
  • 1

1 Answers1

1

There is a good solution to this here: Split string at nth occurrence of a given character

with some small tweaking to that solution (and assuming that the numbers are just to enumerate the delimeters):

>>> string = "||Hello people| ||It can be a sentence too|"
>>> n = 3
>>> groups = text.split('|')
>>> '|'.join(groups[:n]) + '|\n' + '|'.join(groups[n:])
'||Hello people|\n ||It can be a sentence too|'
Community
  • 1
  • 1
stackunderflow
  • 202
  • 1
  • 7