Skip to content

Commit e2204ef

Browse files
committed
py: add str.replace
Signed-off-by: Sebastien Binet <binet@cern.ch>
1 parent 90acd73 commit e2204ef

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

py/string.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,17 @@ func fieldsN(s string, n int) []string {
122122
}
123123

124124
func init() {
125+
StringType.Dict["replace"] = MustNewMethod("replace", func(self Object, args Tuple) (Object, error) {
126+
return self.(String).Replace(args)
127+
}, 0, `replace(self, old, new, count=-1) -> return a copy with all occurrences of substring old replaced by new.
128+
129+
count
130+
Maximum number of occurrences to replace.
131+
-1 (the default value) means replace all occurrences.
132+
133+
If the optional argument count is given, only the first count occurrences are
134+
replaced.`)
135+
125136
StringType.Dict["split"] = MustNewMethod("split", func(self Object, args Tuple, kwargs StringDict) (Object, error) {
126137
return self.(String).Split(args, kwargs)
127138
}, 0, "split(sub) -> split string with sub.")
@@ -598,6 +609,26 @@ func (s String) Split(args Tuple, kwargs StringDict) (Object, error) {
598609
return &o, nil
599610
}
600611

612+
func (s String) Replace(args Tuple) (Object, error) {
613+
var (
614+
pyold Object = None
615+
pynew Object = None
616+
pycnt Object = Int(-1)
617+
)
618+
err := ParseTuple(args, "ss|i:replace", &pyold, &pynew, &pycnt)
619+
if err != nil {
620+
return nil, err
621+
}
622+
623+
var (
624+
old = string(pyold.(String))
625+
new = string(pynew.(String))
626+
cnt = int(pycnt.(Int))
627+
)
628+
629+
return String(strings.Replace(string(s), old, new, cnt)), nil
630+
}
631+
601632
// Check stringerface is satisfied
602633
var (
603634
_ richComparison = String("")

0 commit comments

Comments
 (0)