Python Create a class for implementing basic string operations: search, replace, reverse, etc.

Document 对象参考手册Python3 Examples

We will create a class namedStringOperationswhich contains several basic string operation methods, including finding substrings, replacing substrings, and reversing strings.

Example

class StringOperations:
    def __init__(self, text):
        self.text = text

    def find_substring(self, substring):
        return self.text.find(substring)

    def replace_substring(self, old_substring, new_substring):
        return self.text.replace(old_substring, new_substring)

    def reverse_string(self):
        return self.text[::-1]

# Example usage
text = "Hello, World!"
string_ops = StringOperations(text)

# Find substring
print("Substring 'World' found at index:", string_ops.find_substring("World"))

# Replace substring
new_text = string_ops.replace_substring("World", "Python")
print("After replacement:", new_text)

# Reverse string
reversed_text = string_ops.reverse_string()
print("Reversed string:", reversed_text)

Code explanation:

  1. __init__Method: This is the constructor of the class, used to initialize an instance of the class. It accepts a stringtextand stores it in the instance variableself.text.
  2. find_substringMethod: This method uses Python's built-infindmethod to find the position of the substring in the original string. If found, it returns the starting index of the substring; otherwise, it returns -1.
  3. replace_substringMethod: This method uses Python's built-inreplacemethod to replace a substring in the string. It accepts two parameters: the old substring to be replaced and the new substring, and returns the new string after replacement.
  4. reverse_stringMethod: This method uses Python's slicing operation[::-1]to reverse the string, and returns the reversed string.

Output result:

Substring 'World' found at index: 7
After replacement: Hello, Python!
Reversed string: !dlroW ,olleH

Document 对象参考手册Python3 Examples

Other extensions