...
 
Commits (50)
This diff is collapsed.
This diff is collapsed.
......@@ -10,8 +10,7 @@ import traceback
from math import log10, floor
import re
import numpy as np
import glob
import mmap
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
......@@ -202,3 +201,37 @@ def find_str_in_files(filename_pattern_path, string, contains_str=True):
files.remove(f)
return files
def replace_nth(string, old, new, n=1, option='only nth'):
"""
This function replaces occurrences of string 'old' with string 'new'.
There are three types of replacement of string 'old':
1) 'only nth' replaces only nth occurrence (default).
2) 'all left' replaces nth occurrence and all occurrences to the left.
3) 'all right' replaces nth occurrence and all occurrences to the right.
"""
if option == 'only nth':
left_join = old
right_join = old
elif option == 'all left':
left_join = new
right_join = old
elif option == 'all right':
left_join = old
right_join = new
else:
print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")
return None
groups = string.split(old)
nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]
return new.join(nth_split)
def replace_every_nth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n - 1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted)
new_string = before + after
return new_string