Skip to content
This repository has been archived by the owner on May 31, 2020. It is now read-only.

Commit

Permalink
add implementation for str.find
Browse files Browse the repository at this point in the history
  • Loading branch information
stummjr committed Nov 6, 2016
1 parent a258101 commit 7ffaa8e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 13 deletions.
33 changes: 20 additions & 13 deletions python/common/org/python/types/Str.java
Expand Up @@ -536,10 +536,22 @@ public org.python.Object expandtabs() {
}

@org.python.Method(
__doc__ = ""
__doc__ = "S.find(sub[, start[, end]]) -> int",
args = {"item"},
default_args = {"start", "end"}
)
public org.python.Object find() {
throw new org.python.exceptions.NotImplementedError("find() has not been implemented.");
public org.python.Object find(org.python.Object item, org.python.Object start, org.python.Object end) {
if (start == null) {
start = new Int(0);
}
if (end == null) {
end = new Int(this.value.length());
}
int foundAt = this.__getitem__(new Slice(start, end)).toString().indexOf(item.toString());
if (foundAt >= 0) {
return new Int(foundAt + toPositiveIndex(((Int) start).value));
}
return new Int(foundAt);
}

@org.python.Method(
Expand Down Expand Up @@ -569,17 +581,12 @@ private long toPositiveIndex(long index) {
default_args = {"start", "end"}
)
public org.python.Object index(org.python.Object item, org.python.Object start, org.python.Object end) {
if (start == null) {
start = new Int(0);
}
if (end == null) {
end = new Int(this.value.length());
}
int foundAt = this.__getitem__(new Slice(start, end)).toString().indexOf(item.toString());
if (foundAt >= 0) {
return new Int(foundAt + toPositiveIndex(((Int) start).value));
org.python.Object foundAt = this.find(item, start, end);
if (((Int)foundAt).value < 0) {
throw new org.python.exceptions.ValueError("substring not found");
} else {
return foundAt;
}
throw new org.python.exceptions.ValueError("substring not found");
}

@org.python.Method(
Expand Down
36 changes: 36 additions & 0 deletions tests/datatypes/test_str.py
Expand Up @@ -171,6 +171,42 @@ def test_count(self):
print(s.count('hell', -4))
""")

def test_find(self):
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell'))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('world'))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, 3))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, 100))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, -1))
""")

self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', -4))
""")


class UnaryStrOperationTests(UnaryOperationTestCase, TranspileTestCase):
data_type = 'str'
Expand Down

0 comments on commit 7ffaa8e

Please sign in to comment.