Kaynağa Gözat

`str.index` and `str.find` supports `__start`

blueloveTH 2 yıl önce
ebeveyn
işleme
0df619b66f
2 değiştirilmiş dosya ile 28 ekleme ve 7 silme
  1. 9 7
      src/pocketpy.cpp
  2. 19 0
      tests/04_str.py

+ 9 - 7
src/pocketpy.cpp

@@ -594,18 +594,20 @@ void init_builtins(VM* _vm) {
         return VAR(self.count(s));
     });
 
-    _vm->bind_method<1>(VM::tp_str, "index", [](VM* vm, ArgsView args) {
+    _vm->bind(_vm->_t(VM::tp_str), "index(self, value, __start=0)", [](VM* vm, ArgsView args) {
         const Str& self = _CAST(Str&, args[0]);
-        const Str& sub = CAST(Str&, args[1]);
-        int index = self.index(sub);
-        if(index == -1) vm->ValueError("substring not found");
+        const Str& value = CAST(Str&, args[1]);
+        int start = CAST(int, args[2]);
+        int index = self.index(value, start);
+        if(index < 0) vm->ValueError("substring not found");
         return VAR(index);
     });
 
-    _vm->bind_method<1>(VM::tp_str, "find", [](VM* vm, ArgsView args) {
+    _vm->bind(_vm->_t(VM::tp_str), "find(self, value, __start=0)", [](VM* vm, ArgsView args) {
         const Str& self = _CAST(Str&, args[0]);
-        const Str& sub = CAST(Str&, args[1]);
-        return VAR(self.index(sub));
+        const Str& value = CAST(Str&, args[1]);
+        int start = CAST(int, args[2]);
+        return VAR(self.index(value, start));
     });
 
     _vm->bind_method<1>(VM::tp_str, "startswith", [](VM* vm, ArgsView args) {

+ 19 - 0
tests/04_str.py

@@ -223,3 +223,22 @@ test(0, 100000)
 test(-100, 100)
 test(-100000, 100000)
 test(-2**30, 2**30)
+
+
+a = '123'
+assert a.index('2') == 1
+assert a.index('1') == 0
+assert a.index('3') == 2
+
+assert a.index('2', 1) == 1
+assert a.index('1', 0) == 0
+
+try:
+    a.index('1', 1)
+    exit(1)
+except ValueError:
+    pass
+
+assert a.find('1') == 0
+assert a.find('1', 1) == -1
+