2

How would I go about writing python functions that can be append to strings (or other object)?

for example:

"FOO".lower()

How do they receive input? Are they generators?

I will happily read up on it, but I don't really know what I am looking for.

Marcin
  • 48,559
  • 18
  • 128
  • 201
beoliver
  • 5,579
  • 5
  • 36
  • 72

2 Answers2

6

Strings are objects and thus have methods. lower() is one of them.

You cannot add a custom method to str, unicode or any other builtin (written in C) classes - see Implementing a custom string method and Extending builtin classes in python

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • thanks... I feel really stupid now, completely forgot that str was it's own class! make's far more sense! – beoliver Mar 20 '12 at 10:46
2

They are not generators. They are simply methods defined on the string class.

You could create your own like this:

>>> class MyString(str):
...   def reversed(self):
...     return self[::-1]
... 
>>> x = MyString('spam and eggs')
>>> x.reversed()
'sgge dna maps'
wim
  • 338,267
  • 99
  • 616
  • 750