Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Create a Class for Basic String Operations: Find, Replace, Reverse, etc.

Python Create a Class for Basic String Operations: Find, Replace, Reverse, etc.

Document Object Reference Manual Python3 Examples

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

print

(

"Substring 'World' found at index:"

,

string_ops.

find_substring

(

"World"

)

)

Replace a 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 analysis:

  1. __init__ method: this is the class constructor, used to initialize an instance of the class. It takes a string text and stores it in the instance variable self.text it.
  2. find_substring method: this method uses Python's built-in find method 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.
  3. replace_substring method: this method uses Python's built-in replace method 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.
  4. reverse_string method: 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

Document Object Reference Manual Python3 Examples