In Python, you cannot directly add methods to built-in types like str (this is called "monkey patching" and is not allowed for built-in types implemented in C, like str, int, etc.).
However, you have a few alternatives:
1. Subclass str
You can create your own subclass of str and add the method there:
class MyStr(str):
def format_str(self):
return self.strip()
# Usage:
a = MyStr(" hello ")
print(a.format_str()) # Output: "hello"
2. Use a Standalone Function
If you want to use it with normal strings, just define a function:
def format_str(s: str) -> str:
return s.strip()
# Usage:
a = " hello "
print(format_str(a)) # Output: "hello"
3. Use Extension Libraries
Some libraries like forbiddenfruit allow monkey-patching built-in types, but this is not recommended for production code as it can lead to unexpected behavior and is generally considered bad practice.
4. Use a Wrapper Class
You can create a wrapper class that holds a string and provides extra methods:
class StringWrapper:
def __init__(self, s: str):
self.s = s
def format_str(self):
return self.s.strip()
# Usage:
a = StringWrapper(" hello ")
print(a.format_str()) # Output: "hello"
Summary
- You cannot add methods to
str directly.
- Use a subclass, a wrapper, or a standalone function.
If you want to use a.format_str() syntax, subclassing is the most Pythonic way.
If you want to use it with all strings, use a function.