Skip to content

Commit 1eacefe

Browse files
committed
Implement simplest case of str.startswith().
1 parent b979122 commit 1eacefe

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

py/objstr.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,16 @@ static mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
278278
}
279279
}
280280

281+
// TODO: (Much) more variety in args
282+
static mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
283+
GET_STR_DATA_LEN(self_in, str, str_len);
284+
GET_STR_DATA_LEN(arg, prefix, prefix_len);
285+
if (prefix_len > str_len) {
286+
return mp_const_false;
287+
}
288+
return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
289+
}
290+
281291
static bool chr_in_str(const byte* const str, const size_t str_len, int c) {
282292
for (size_t i = 0; i < str_len; i++) {
283293
if (str[i] == c) {
@@ -364,13 +374,15 @@ mp_obj_t str_format(uint n_args, const mp_obj_t *args) {
364374
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
365375
static MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
366376
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
377+
static MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
367378
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
368379
static MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format);
369380

370381
static const mp_method_t str_type_methods[] = {
371382
{ "find", &str_find_obj },
372383
{ "join", &str_join_obj },
373384
{ "split", &str_split_obj },
385+
{ "startswith", &str_startswith_obj },
374386
{ "strip", &str_strip_obj },
375387
{ "format", &str_format_obj },
376388
{ NULL, NULL }, // end-of-list sentinel

tests/basics/string_startswith.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
print("foobar".startswith("foo"))
2+
print("foobar".startswith("Foo"))
3+
print("foobar".startswith("foo1"))
4+
print("foobar".startswith("foobar"))
5+
print("foobar".startswith(""))

0 commit comments

Comments
 (0)