Skip to content

Commit 7380a83

Browse files
committed
str: Implement proper string (instead of byte string) indexing.
Also, support negative indexes.
1 parent 545591a commit 7380a83

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

py/objstr.c

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,8 @@ mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
4444
// TODO: need predicate to check for int-like type (bools are such for example)
4545
// ["no", "yes"][1 == 2] is common idiom
4646
if (MP_OBJ_IS_SMALL_INT(rhs_in)) {
47-
// TODO: This implements byte string access for single index so far
48-
// TODO: Handle negative indexes.
49-
return mp_obj_new_int(lhs_str[mp_obj_get_int(rhs_in)]);
47+
uint index = mp_get_index(lhs->base.type, strlen(lhs_str), rhs_in);
48+
return mp_obj_new_str(qstr_from_strn_copy(lhs_str + index, 1));
5049
#if MICROPY_ENABLE_SLICE
5150
} else if (MP_OBJ_IS_TYPE(rhs_in, &slice_type)) {
5251
machine_int_t start, stop, step;

tests/basics/string1.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@
1010

1111
print('123' * 5)
1212

13+
print('abc'[1])
14+
print('abc'[-1])
15+
try:
16+
'abc'[100]
17+
except IndexError:
18+
print('caught')
19+
try:
20+
'abc'[-4]
21+
except IndexError:
22+
print('caught2')
23+
1324
# iter
1425
print(list('str'))
1526

0 commit comments

Comments
 (0)