Remove an Exclamation Mark from the End of String using Python

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"
Code language: Python (python)

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)
Code language: Python (python)

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 ""
Code language: Python (python)

Option 2 (using endswith):

def remove(s): return s[:-1] if s.endswith('!') else s
Code language: Python (python)

Option 3 (simple):

def remove(s): return s[:-1] if s and s[-1] == '!' else s
Code language: Python (python)

Option 4 (using regex):

def remove(s): import re return re.sub(r'!$', '', s)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Brent
Brent
9 months ago

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.

Wes Turner
Wes Turner
9 months ago

Python 3.9 has a str.removesuffix() method:

def remove(s):
return s.removesuffix(‘!’)

https://www.python.org/dev/peps/pep-0616/