Enroy
Enroy

Reputation: 17

Understanding why we use methods on strings in Python

I've just started learning Python and I've got to a point where I'm a little confused on why we use .upper() in, for example, print("Hello, World!".upper()). I've read through some answers provided on similar stackoverflow questions, any they all the general theme, "you use the notation .upper() for methods".

From my understanding, methods are just special cases of functions that belong to classes. If this is the case, why do we use things like .upper(), .title(), .isalhpa() etc. on simple strings like "Hello, World!" when they don't belong to a class?

Upvotes: 0

Views: 374

Answers (2)

bla
bla

Reputation: 1870

As other people have pointed out this happens because in python strings, as all of the other types I am aware of, are objects. Strings specifically are objects of the str class. You may look here for more on this.

Also methods usually refer to functions bound to objects. This excellent post about how methods work on python may interest you.

Upvotes: 2

David Norrish
David Norrish

Reputation: 357

A good thing to get comfortable with is checking types and methods of different objects. E.g.

>>> stringy = 'Hello world!'
>>> type(stringy)
str

Then to get information on string-type objects:

>>> help(str)
class str(object)
# <A description of the class will be here>

Methods defined here:
# <various methods>
upper(...)
    S.upper() -> str

    Return a copy of S converted to uppercase.

So what we were actually doing in our first line is creating an object of the str() class:

stringy = str('Hello world!')

Hope that makes sense :-)

Upvotes: 1

Related Questions