How can I remove a sub-string (a prefix) from a array of string elements? (remove the sub string from each element)
The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .
removeprefix(prefix, /) function which removes the prefix and returns the rest of the string. If the prefix string is not found then it returns the original string. It is introduced in Python 3.9. 0 version. Syntax: str.removeprefix(prefix, /)
Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.
Using RegExp
and ^
to ensure it is the prefix and not just somewhere in the string:
var arr = ['a1', 'a2', 'a54a']; for(var i = 0, len = arr.length; i < len; i++) { arr[i] = arr[i].replace(/^a/, ''); } arr; // '1,2,54a' removing the 'a' at the begining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With