Search⌘ K
AI Features

Solution: Define a Class that Performs Operations on a String

Explore how to create a Python class designed for string operations. Understand initializing data members, retrieving string values, overloading operators for concatenation, and methods for converting strings to uppercase and lowercase.

We'll cover the following...

The solution to the problem of defining a class that performs operations on a string in Python is given below.

Solution

Python 3.8
class String :
def __init__(self, x) :
self.s = x
def getString(self) :
return self.s
def __iadd__(self, other) :
self.s = self.s + other.s
return self
def toUpper(self) :
self.s = self.s.upper( )
def toLower(self) :
self.s = self.s.lower( )
a = String('www.abcd')
b = String('.com')
a += b
print("Concatenated string:",a.getString())
a.toUpper( )
print("Lower to upper:",a.getString())
a.toLower( )
print("Upper to lower:",a.getString())

Explanation

...