@@ -817,6 +817,23 @@ STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
817817 return str_uni_strip (RSTRIP , n_args , args );
818818}
819819
820+ #if MICROPY_PY_BUILTINS_STR_CENTER
821+ STATIC mp_obj_t str_center (mp_obj_t str_in , mp_obj_t width_in ) {
822+ GET_STR_DATA_LEN (str_in , str , str_len );
823+ int width = mp_obj_get_int (width_in );
824+ if (str_len >= width ) {
825+ return str_in ;
826+ }
827+
828+ vstr_t vstr ;
829+ vstr_init_len (& vstr , width );
830+ memset (vstr .buf , ' ' , width );
831+ int left = (width - str_len ) / 2 ;
832+ memcpy (vstr .buf + left , str , str_len );
833+ return mp_obj_new_str_from_vstr (mp_obj_get_type (str_in ), & vstr );
834+ }
835+ #endif
836+
820837// Takes an int arg, but only parses unsigned numbers, and only changes
821838// *num if at least one digit was parsed.
822839STATIC const char * str_to_int (const char * str , const char * top , int * num ) {
@@ -1846,6 +1863,9 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
18461863#if MICROPY_PY_BUILTINS_STR_SPLITLINES
18471864MP_DEFINE_CONST_FUN_OBJ_KW (str_splitlines_obj , 1 , str_splitlines );
18481865#endif
1866+ #if MICROPY_PY_BUILTINS_STR_CENTER
1867+ MP_DEFINE_CONST_FUN_OBJ_2 (str_center_obj , str_center );
1868+ #endif
18491869MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_rsplit_obj , 1 , 3 , str_rsplit );
18501870MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_startswith_obj , 2 , 3 , str_startswith );
18511871MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (str_endswith_obj , 2 , 3 , str_endswith );
@@ -1897,6 +1917,7 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
18971917 { MP_ROM_QSTR (MP_QSTR_count ), MP_ROM_PTR (& str_count_obj ) },
18981918 { MP_ROM_QSTR (MP_QSTR_partition ), MP_ROM_PTR (& str_partition_obj ) },
18991919 { MP_ROM_QSTR (MP_QSTR_rpartition ), MP_ROM_PTR (& str_rpartition_obj ) },
1920+ { MP_ROM_QSTR (MP_QSTR_center ), MP_ROM_PTR (& str_center_obj ) },
19001921 { MP_ROM_QSTR (MP_QSTR_lower ), MP_ROM_PTR (& str_lower_obj ) },
19011922 { MP_ROM_QSTR (MP_QSTR_upper ), MP_ROM_PTR (& str_upper_obj ) },
19021923 { MP_ROM_QSTR (MP_QSTR_isspace ), MP_ROM_PTR (& str_isspace_obj ) },
0 commit comments