Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

Python में String के End से Substring कैसे Remove करें?


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

  1. - नॉन-एम्प्टी स्ट्रिंग से nवें इंडेक्स कैरेक्टर को हटाने का पायथन प्रोग्राम

    जब किसी स्ट्रिंग से जो खाली नहीं है, एक विशिष्ट इंडेक्स कैरेक्टर को हटाना हो, तो इस पर पुनरावृति की जा सकती है और जब इंडेक्स मेल नहीं खाता तो उस कैरेक्टर को दूसरी स्ट्रिंग में संग्रहीत किया जा सकता है। उदाहरण my_string = Hi there how are you print(स्ट्रिंग है:) print(my_string) index_removed = 2 ch

  1. - पायथन में लिस्ट से एलिमेंट कैसे हटाएं

    पायथन में लिस्ट एक लीनियर डेटा स्ट्रक्चर है जहां एलिमेंट्स सन्निहित मेमोरी लोकेशन्स में स्टोर होते हैं और एलिमेंट्स को उनके इंडेक्स द्वारा एक्सेस किया जाता है। हमें कभी-कभी पायथन में लिस्ट से एलिमेंट हटाने की आवश्यकता होती है। इसे प्राप्त करने के लिए विभिन्न इनबिल्ट फंक्शन्स हैं। pop() यह pop() मे

  1. Python में Label से Text कैसे Remove करें? Python में Label से Text कैसे Remove करें?

    Tkinter GUI-based applications बनाने और develop करने के लिए एक Python library है। इस लेख में, हम देखेंगे कि कुछ text वाले Label से text कैसे remove करें। Label से text remove करने के लिए, हम एक associated button बनाएंगे जो Label के लिए trigger के रूप में कार्य करेगा। उदाहरण # Import Tkinter Library