0

I am using Python's strip method to remove a substring from string. Below is the example.

test = "router_sdkf12e"
print(test.strip("router_"))

Output : sdkf12

Issue : 'e' from the end of string is getting remove. However if there is some other letter other than 'e', then that letter is not removed. Why such weird behavior?

test = "router_sdkf12a"
print(test.strip("router_"))

Output : sdkf12a

Regards, Rahul Kumbhar

Rahul Kumbhar
  • 69
  • 1
  • 3
  • given the string `"router_sdkf12z"` - what is your expected output? – balderman Oct 21 '21 at 07:53
  • 1
    `strip` removes the *characters* `eortu_` from either side of the string. It removes a set of **characters**, not the *substring* "router_". – deceze Oct 21 '21 at 07:55
  • 2
    `print(text.removeprefix("router_"))` – khelwood Oct 21 '21 at 07:56
  • the only nuissance is that `removeprefix` came with Python 3.9, won't work in earlier versions – VPfB Oct 21 '21 at 08:01
  • 1
    Before 3.9 `if text.startswith("router_"): text = text[7:]` – khelwood Oct 21 '21 at 08:02
  • strip command removes `characters`(!) in the end of the string which are provided as "router_". So the last letter in result will be which is in the source string but not in ['r', 'o', 'u', 't', 'e', '_']. Ex. if you provide `router_sdkf12ero_ut` the result will be `sdkf12` as well. To remove a substring please use test.replace("router_", "") – barbariania Oct 21 '21 at 08:11

0 Answers0