Skip to content

Commit 9d70597

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

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

py/bytes.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,9 +258,43 @@ func (a Bytes) M__iadd__(other Object) (Object, error) {
258258
return NotImplemented, nil
259259
}
260260

261+
func (a Bytes) Replace(args Tuple) (Object, error) {
262+
var (
263+
pyold Object = None
264+
pynew Object = None
265+
pycnt Object = Int(-1)
266+
)
267+
err := ParseTuple(args, "yy|i:replace", &pyold, &pynew, &pycnt)
268+
if err != nil {
269+
return nil, err
270+
}
271+
272+
var (
273+
old = []byte(pyold.(Bytes))
274+
new = []byte(pynew.(Bytes))
275+
cnt = int(pycnt.(Int))
276+
)
277+
278+
return Bytes(bytes.Replace([]byte(a), old, new, cnt)), nil
279+
}
280+
261281
// Check interface is satisfied
262282
var (
263283
_ richComparison = (Bytes)(nil)
264284
_ I__add__ = (Bytes)(nil)
265285
_ I__iadd__ = (Bytes)(nil)
266286
)
287+
288+
func init() {
289+
BytesType.Dict["replace"] = MustNewMethod("replace", func(self Object, args Tuple) (Object, error) {
290+
return self.(Bytes).Replace(args)
291+
}, 0, `replace(self, old, new, count=-1) -> return a copy with all occurrences of substring old replaced by new.
292+
293+
count
294+
Maximum number of occurrences to replace.
295+
-1 (the default value) means replace all occurrences.
296+
297+
If the optional argument count is given, only the first count occurrences are
298+
replaced.`)
299+
300+
}

0 commit comments

Comments
 (0)