String helper methods

replace_string_by_indices[source]

replace_string_by_indices(string, replace_ranges, replace_with)

Replace parts of string at the specified locations

Parameters

  • string - str
  • replace_ranges - Either list of (list or tuple) of int's or a single (list or tuple) of int's.
    • Each list or tuple is of one or two int's. In particular, [a,b] or (a,b) Means that string[a:b] is to be replaced. [a] means that string[a:] is to be replaced.
    • The ranges should not overlap and should be arranged in chronological order.
  • replace_with - Either list of str's or a single str
    • The str's which will replace the parts represented by replace_ranges.

examples

example = replace_string_by_indices('ash ketchup', replace_ranges=[[4]], replace_with=["ketchum"])
assert 'ash ketchum' == example
example = replace_string_by_indices('a tupo', replace_ranges=[[3,4]], replace_with = ['y'])
assert 'a typo' == example
example = replace_string_by_indices('hello world!', replace_ranges = [[0,5], [6,12]], replace_with=['goodbye', 'universe!'])
assert 'goodbye universe!' == example, example

# With a single range / str's to replace with
assert 'ash ketchum' == replace_string_by_indices('ash ketchup', replace_ranges=[4], replace_with="ketchum")
assert 'a typo' == replace_string_by_indices('a tupo', replace_ranges=[3,4], replace_with = 'y')

assert 'no problem' == replace_string_by_indices('no problem', [], [])