Remove an Exclamation Mark from the End of String using Python

The challenge

Remove a exclamation mark from the end of string. For a beginner kata, 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)
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Brent
Brent
2 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
2 months ago

Python 3.9 has a str.removesuffix() method:

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

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