@@ -520,6 +520,31 @@ STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
520520 return MP_OBJ_NEW_SMALL_INT (num_occurrences );
521521}
522522
523+ STATIC mp_obj_t str_partition (mp_obj_t self_in , mp_obj_t arg ) {
524+ assert (MP_OBJ_IS_STR (self_in ));
525+ if (!MP_OBJ_IS_STR (arg )) {
526+ nlr_jump (mp_obj_new_exception_msg_varg (& mp_type_TypeError ,
527+ "Can't convert '%s' object to str implicitly" , mp_obj_get_type_str (arg )));
528+ }
529+
530+ GET_STR_DATA_LEN (self_in , str , str_len );
531+ GET_STR_DATA_LEN (arg , sep , sep_len );
532+
533+ if (sep_len == 0 ) {
534+ nlr_jump (mp_obj_new_exception_msg (& mp_type_ValueError , "empty separator" ));
535+ }
536+
537+ for (machine_uint_t str_index = 0 ; str_index + sep_len <= str_len ; str_index ++ ) {
538+ if (memcmp (& str [str_index ], sep , sep_len ) == 0 ) {
539+ mp_obj_t items [] = {mp_obj_new_str (str , str_index , false), arg ,
540+ mp_obj_new_str (str + str_index + sep_len , str_len - str_index - sep_len , false)};
541+ return mp_obj_new_tuple (3 , items );
542+ }
543+ }
544+ mp_obj_t items [] = {mp_obj_new_str (str , str_len , false), MP_OBJ_NEW_QSTR (MP_QSTR_ ), MP_OBJ_NEW_QSTR (MP_QSTR_ )};
545+ return mp_obj_new_tuple (3 , items );
546+ }
547+
523548STATIC machine_int_t str_get_buffer (mp_obj_t self_in , buffer_info_t * bufinfo , int flags ) {
524549 if (flags == BUFFER_READ ) {
525550 GET_STR_DATA_LEN (self_in , str_data , str_len );
@@ -542,6 +567,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
542567STATIC MP_DEFINE_CONST_FUN_OBJ_VAR (str_format_obj , 1 , str_format );
543568STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_replace_obj , 3 , 4 , str_replace );
544569STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_count_obj , 2 , 4 , str_count );
570+ STATIC MP_DEFINE_CONST_FUN_OBJ_2 (str_partition_obj , str_partition );
545571
546572STATIC const mp_method_t str_type_methods [] = {
547573 { "find" , & str_find_obj },
@@ -552,6 +578,7 @@ STATIC const mp_method_t str_type_methods[] = {
552578 { "format" , & str_format_obj },
553579 { "replace" , & str_replace_obj },
554580 { "count" , & str_count_obj },
581+ { "partition" , & str_partition_obj },
555582 { NULL , NULL }, // end-of-list sentinel
556583};
557584
0 commit comments