class TStr:
def __init__(self, chars: str = '') -> None:
self.chars = tuple(chars)
def __len__(self) -> int:
return len(self.chars)
def __str__(self) -> str:
return ''.join(self.chars)
def __repr__(self) -> str:
return f'{type(self).__name__}("{self}")'
def __add__(self, s) -> 'TStr':
return TStr(self.chars + s.chars)
def __mul__(self, n: int) -> 'TStr':
return TStr(n * self.chars)
def __rmul__(self, n: int) -> 'TStr':
return TStr(n * self.chars)
def __eq__(self, x: object) -> bool:
return self.chars == x.chars
def __lt__(self, x: 'TStr') -> bool:
return self.chars < x.chars
def __le__(self, x: 'TStr') -> bool:
return self == x or self < x
def __hash__(self) -> int:
return hash(self.chars)
def __getitem__(self, i: int) -> 'TStr':
return TStr(self.chars[i])
def find(self, x: 'TStr') -> int:
return next((i for i in range(len(self) - len(x) + 1) if self[i:i + len(x)] == x), -1)
def __contains__(self, x: 'TStr') -> bool:
return self.find(x) >= 0
def startswith(self, prefix: 'TStr') -> bool:
return self[:len(prefix)] == prefix
def endswith(self, suffix: 'TStr') -> bool:
return self[-len(suffix):] == suffix
def replace(self, old: 'TStr', new: 'TStr') -> 'TStr':
k = self.find(old)
return self[:k] + new + self[k+len(old):].replace(old, new) if k >= 0 else self
hello = TStr('Hello')
world = TStr('World!')
space = TStr(' ')
hello_world = hello + space + world
for w in hello, space, world, space+hello:
print(hello_world.find(w))
print()
for w in hello, space, world, space+hello:
print(w in hello_world)
print()
for w in hello, space, world, hello+space:
print(hello_world.startswith(w))
print()
for w in world, hello, space, space+world:
print(hello_world.endswith(w))
print()
print(hello_world.replace(TStr('l'), TStr('L')*3))