DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on

removesuffix in Python

Buy Me a Coffee

*Memo:

  • My post explains string, bytes and bytearray functions.

str.removesuffix() and bytes.removesuffix() or bytearray.removesuffix() can remove the suffix of the string and bytes or bytearray respectively as shown below:

*Memo:

  • The 1st argument is suffix(Required-Type:str for str.removesuffix() or Bytes-like object for bytes.removesuffix() and bytearray.removesuffix()):
    • It's the suffix of zero or more characters and bytes respectively.
    • Don't use suffix=.

<String>:

v = 'hello world'

print(v.removesuffix('ld'))
# hello wor

print(v.removesuffix(' world'))
# hello

print(v.removesuffix('lo world'))
# hel

print(v.removesuffix('LD'))
print(v.removesuffix(''))
print(v.removesuffix('abc'))
# hello world
Enter fullscreen mode Exit fullscreen mode

<Bytes & Bytearray>:

bytes:

v = b'hello world'

print(v.removesuffix(b'ld'))
print(v.removesuffix(bytearray(b'ld')))
# b'hello wor'

print(v.removesuffix(b' world'))
print(v.removesuffix(bytearray(b' world')))
# b'hello'

print(v.removesuffix(b'lo world'))
print(v.removesuffix(bytearray(b'lo world')))
# b'hel'

print(v.removesuffix(b'LD'))
print(v.removesuffix(bytearray(b'LD')))
print(v.removesuffix(b''))
print(v.removesuffix(bytearray(b'')))
print(v.removesuffix(b'abc'))
print(v.removesuffix(bytearray(b'abc')))
# b'hello world'
Enter fullscreen mode Exit fullscreen mode

bytearray:

v = bytearray(b'hello world')

print(v.removesuffix(b'ld'))
print(v.removesuffix(bytearray(b'ld')))
# bytearray(b'hello wor')

print(v.removesuffix(b' world'))
print(v.removesuffix(bytearray(b' world')))
# bytearray(b'hello')

print(v.removesuffix(b'lo world'))
print(v.removesuffix(bytearray(b'lo world')))
# bytearray(b'hel')

print(v.removesuffix(b'LD'))
print(v.removesuffix(bytearray(b'LD')))
print(v.removesuffix(b''))
print(v.removesuffix(bytearray(b'')))
print(v.removesuffix(b'abc'))
print(v.removesuffix(bytearray(b'abc')))
# bytearray(b'hello world')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)