Skip to content

Commit e8e5cf7

Browse files
committed
py: add bytes.replace
Signed-off-by: Sebastien Binet <[email protected]>
1 parent 06c9fbe commit e8e5cf7

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
@@ -240,5 +240,39 @@ func (a Bytes) M__ge__(other Object) (Object, error) {
240240
return NotImplemented, nil
241241
}
242242

243+
func (a Bytes) Replace(args Tuple) (Object, error) {
244+
var (
245+
pyold Object = None
246+
pynew Object = None
247+
pycnt Object = Int(-1)
248+
)
249+
err := ParseTuple(args, "yy|i:replace", &pyold, &pynew, &pycnt)
250+
if err != nil {
251+
return nil, err
252+
}
253+
254+
var (
255+
old = []byte(pyold.(Bytes))
256+
new = []byte(pynew.(Bytes))
257+
cnt = int(pycnt.(Int))
258+
)
259+
260+
return Bytes(bytes.Replace([]byte(a), old, new, cnt)), nil
261+
}
262+
243263
// Check interface is satisfied
244264
var _ richComparison = (Bytes)(nil)
265+
266+
func init() {
267+
BytesType.Dict["replace"] = MustNewMethod("replace", func(self Object, args Tuple) (Object, error) {
268+
return self.(Bytes).Replace(args)
269+
}, 0, `replace(self, old, new, count=-1) -> return a copy with all occurrences of substring old replaced by new.
270+
271+
count
272+
Maximum number of occurrences to replace.
273+
-1 (the default value) means replace all occurrences.
274+
275+
If the optional argument count is given, only the first count occurrences are
276+
replaced.`)
277+
278+
}

0 commit comments

Comments
 (0)