Python Create a Class for Basic String Operations: Find, Replace, Reverse, etc.
We will create a class named StringOperations class containing several basic string operation methods, including finding a substring, replacing a substring and reversing a string.
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 a substring
(
"Substring 'World' found at index:"
,
string_ops.
find_substring
(
"World"
)
)
Replace a substring
new_text
=
string_ops.
replace_substring
(
"World"
,
"Python"
)
(
"After replacement:"
,
new_text
)
Reverse String
reversed_text
=
string_ops.
reverse_string
(
)
(
"Reversed string:"
,
reversed_text
)
Code analysis:
__init__method: this is the class constructor, used to initialize an instance of the class. It takes a stringtextand stores it in the instance variableself.textit.find_substringmethod: this method uses Python's built-infindmethod to find the position of a 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 a string. It takes 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 slice 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
Python3 Examples