Thanks to visit codestin.com
Credit goes to github.com

Skip to content

py: Implement str.count #244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions py/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ func init() {
return Bool(false), nil
}, 0, "endswith(suffix[, start[, end]]) -> bool")

StringType.Dict["count"] = MustNewMethod("count", func(self Object, args Tuple) (Object, error) {
return self.(String).Count(args)
}, 0, `count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.`)

StringType.Dict["find"] = MustNewMethod("find", func(self Object, args Tuple) (Object, error) {
return self.(String).find(args)
}, 0, `find(...)
Expand Down Expand Up @@ -612,6 +619,40 @@ func (s String) M__contains__(item Object) (Object, error) {
return NewBool(strings.Contains(string(s), string(needle))), nil
}

func (s String) Count(args Tuple) (Object, error) {
var (
pysub Object
pybeg Object = Int(0)
pyend Object = Int(s.len())
pyfmt = "s|ii:count"
)
err := ParseTuple(args, pyfmt, &pysub, &pybeg, &pyend)
if err != nil {
return nil, err
}

var (
beg = int(pybeg.(Int))
end = int(pyend.(Int))
size = s.len()
)
if beg > size {
beg = size
}
if end < 0 {
end = size
}
if end > size {
end = size
}

var (
str = string(s.slice(beg, end, s.len()))
sub = string(pysub.(String))
)
return Int(strings.Count(str, sub)), nil
}

func (s String) find(args Tuple) (Object, error) {
var (
pysub Object
Expand Down
9 changes: 9 additions & 0 deletions py/tests/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -944,5 +944,14 @@ def __index__(self):
else:
assert False, "TypeError not raised"

doc="count"
assert 'hello world'.count('l') == 3
assert 'hello world'.count('l', 3) == 2
assert 'hello world'.count('l', 3, 10) == 2
assert 'hello world'.count('l', 3, 100) == 2
assert 'hello world'.count('l', 3, 5) == 1
assert 'hello world'.count('l', 3, 1) == 0
assert 'hello world'.count('z') == 0


doc="finished"
Loading