Remove an Exclamation Mark From the End of String Using Python

  • Home /
  • Blog Posts /
  • 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.


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"],

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
        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)