Skip to content

Commit 8827682

Browse files
committed
objstr: *strip(): If nothing is stripped, don't create dup string.
1 parent bcdffe5 commit 8827682

2 files changed

Lines changed: 10 additions & 0 deletions

File tree

py/objstr.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,12 @@ STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
691691
assert(last_good_char_pos >= first_good_char_pos);
692692
//+1 to accomodate the last character
693693
machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
694+
if (stripped_len == orig_str_len) {
695+
// If nothing was stripped, don't bother to dup original string
696+
// TODO: watch out for this case when we'll get to bytearray.strip()
697+
assert(first_good_char_pos == 0);
698+
return args[0];
699+
}
694700
return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
695701
}
696702

tests/basics/string_strip.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,7 @@
3131
print("a ".strip())
3232
print("a ".lstrip())
3333
print("a ".rstrip())
34+
35+
# Test that stripping unstrippable string returns original object
36+
s = "abc"
37+
print(id(s.strip()) == id(s))

0 commit comments

Comments
 (0)