Skip to content
Advertisement

How can i add a new line every nth delimiter of a string in python? [closed]

I am trying to add a new line, for every nth delimiter in a string.

For example i will add a new line every 3rd ‘|’ in the string below:

nthelement = 3
delimiter = '|'
string = 'AB|CD|EEEE|GGg|gger342|gff534|gre343|FGS'
#splitter here
output = 'AB|CD|EEEE|nGGg|gger342|gff534|ngre343|FGS'

Advertisement

Answer

Here is an implementation

def delimit(s, delimiter, n): 
    segments = s.split(delimiter) # splits string by delimiter
    for i, seg in enumerate(segments): 
        if i % n == 0 and i != 0: 
            segments[i] = 'n' + seg # prepend 'n' to segment
    return delimiter.join(segments) # join segments

Usage:

delimit('AB|CD|EEEE|GGg|gger342|gff534|gre343|FGS', '|', 3)
# output: 'AB|CD|EEEE|nGGg|gger342|gff534|ngre343|FGS'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement