Python Create a class for implementing basic string operations: search, replace, reverse, etc.
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)
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:
__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.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.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.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 ,olleHOther extensions
Python3 Examples