The challenge
Remove a exclamation mark from the end of string. You can assume that the input data is always a string, no need to verify it.
Examples
remove("Hi!") === "Hi" remove("Hi!!!") === "Hi!!" remove("!Hi") === "!Hi" remove("!Hi!") === "!Hi" remove("Hi! Hi!") === "Hi! Hi" remove("Hi") === "Hi"
Test cases
test.describe("Basic Tests") tests = [ #[input, [expected]], ["Hi!", "Hi"], ["Hi!!!","Hi!!"], ["!Hi", "!Hi"], ["!Hi!", "!Hi"], ["Hi! Hi!", "Hi! Hi"], ["Hi", "Hi"], ] for inp, exp in tests: test.assert_equals(remove(inp), exp)
The solution in Python
Option 1:
def remove(s): if len(s): return s[:len(s)-1] if s[::-1][0]=="!" else s else: return ""
Option 2 (using endswith
):
def remove(s): return s[:-1] if s.endswith('!') else s
Option 3 (simple
):
def remove(s): return s[:-1] if s and s[-1] == '!' else s
Option 4 (using regex
):
def remove(s): import re return re.sub(r'!$', '', s)
I like option 4.
Its not pretty, but you know when you (re)look at the code, what exactly is being done and the intent.
Python 3.9 has a str.removesuffix() method:
def remove(s):
return s.removesuffix(‘!’)
https://www.python.org/dev/peps/pep-0616/
Thanks for the addition Wes!