String के End से Substring Remove करना
यदि आप String के End से Substring Remove करना चाहते हैं, तो पहले Check करें कि String उस Substring से End होती है या नहीं। यदि करती है, तो String को Slice करके केवल बिना Substring वाला Part रखें।
उदाहरण: Custom Function
def rchop(string, ending):
if string.endswith(ending):
return string[:-len(ending)]
return string
chopped_str = rchop('Hello world', 'orld')
print(chopped_str)
# Output: Hello w
Regex का उपयोग (यदि Speed Important नहीं है):
>>> import re
>>> re.sub('orld$', '', 'Hello world')
'Hello w'
Modern Python: removeprefix/removesuffix (Python 3.9+):
>>> 'Hello world'.removesuffix('orld')
'Hello w'
>>> 'Hello world'.removeprefix('He')
'llo world'
# Multiple Suffixes
>>> 'test.txt'.removesuffix('.txt')
'test'
# Safe - No Error if Suffix नहीं मिलता
>>> 'Hello world'.removesuffix('xyz')
'Hello world'
Backport for Older Python:
def removesuffix(s, suffix):
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s
def removeprefix(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return s
Common Use Case: File Extensions Remove करना
filename = "document.txt"
name = filename.removesuffix('.txt') # Python 3.9+
# या
name = filename[:-4] if filename.endswith('.txt') else filename