mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-20 19:40:18 +00:00
str.index
and str.find
supports __start
This commit is contained in:
parent
96d9e12cd6
commit
0df619b66f
@ -594,18 +594,20 @@ void init_builtins(VM* _vm) {
|
|||||||
return VAR(self.count(s));
|
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& self = _CAST(Str&, args[0]);
|
||||||
const Str& sub = CAST(Str&, args[1]);
|
const Str& value = CAST(Str&, args[1]);
|
||||||
int index = self.index(sub);
|
int start = CAST(int, args[2]);
|
||||||
if(index == -1) vm->ValueError("substring not found");
|
int index = self.index(value, start);
|
||||||
|
if(index < 0) vm->ValueError("substring not found");
|
||||||
return VAR(index);
|
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& self = _CAST(Str&, args[0]);
|
||||||
const Str& sub = CAST(Str&, args[1]);
|
const Str& value = CAST(Str&, args[1]);
|
||||||
return VAR(self.index(sub));
|
int start = CAST(int, args[2]);
|
||||||
|
return VAR(self.index(value, start));
|
||||||
});
|
});
|
||||||
|
|
||||||
_vm->bind_method<1>(VM::tp_str, "startswith", [](VM* vm, ArgsView args) {
|
_vm->bind_method<1>(VM::tp_str, "startswith", [](VM* vm, ArgsView args) {
|
||||||
|
@ -223,3 +223,22 @@ test(0, 100000)
|
|||||||
test(-100, 100)
|
test(-100, 100)
|
||||||
test(-100000, 100000)
|
test(-100000, 100000)
|
||||||
test(-2**30, 2**30)
|
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
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user