Skip to content

Commit c18ef2a

Browse files
committed
objstr: startswith(): Accept optional "start" arg.
1 parent 70328e4 commit c18ef2a

2 files changed

Lines changed: 16 additions & 6 deletions

File tree

py/objstr.c

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -606,13 +606,17 @@ STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
606606
}
607607

608608
// TODO: (Much) more variety in args
609-
STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
610-
GET_STR_DATA_LEN(self_in, str, str_len);
611-
GET_STR_DATA_LEN(arg, prefix, prefix_len);
612-
if (prefix_len > str_len) {
609+
STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
610+
GET_STR_DATA_LEN(args[0], str, str_len);
611+
GET_STR_DATA_LEN(args[1], prefix, prefix_len);
612+
uint index_val = 0;
613+
if (n_args > 2) {
614+
index_val = mp_get_index(&mp_type_str, str_len, args[2], true);
615+
}
616+
if (prefix_len + index_val > str_len) {
613617
return mp_const_false;
614618
}
615-
return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
619+
return MP_BOOL(memcmp(str + index_val, prefix, prefix_len) == 0);
616620
}
617621

618622
enum { LSTRIP, RSTRIP, STRIP };
@@ -1536,7 +1540,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
15361540
STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
15371541
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
15381542
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1539-
STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1543+
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
15401544
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
15411545
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
15421546
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);

tests/basics/string_startswith.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,9 @@
33
print("foobar".startswith("foo1"))
44
print("foobar".startswith("foobar"))
55
print("foobar".startswith(""))
6+
7+
print("1foobar".startswith("foo", 1))
8+
print("1foo".startswith("foo", 1))
9+
print("1foo".startswith("1foo", 1))
10+
print("1fo".startswith("foo", 1))
11+
print("1fo".startswith("foo", 10))

0 commit comments

Comments
 (0)