Python syntax format: var.str() vs str(var)

ReneGe
ReneGe used Ask the Experts™
on
Hi there,

I am new in Python.

I cannot make sense of why these formats are not just the same!

I am not arguing here.  Just trying to understand why these formats are the way they are.

Current format:
len(var)
var.upper()
str(var)
var=var[4]

Why not a standard format like for example:
len(var)
upper(var)
str(var)
middle(var,4)
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Walter RitzelSenior Software Engineer
Commented:
Let's try to explain:
1) len(var) -> the len() function serves to provide the length of a string or lists;
2) var.upper() -> here you are calling method of a string object;
3) str(var) -> again you are calling a function that converts the object that was provided as parameter to its string version.
4) var[4] X middle(var,4) -> here you are taking advantage of the fact that the string could be iterated position by position and instead of calling a function to extract the 4th character, you go there direct.

I think that what makes you confuse is the fact the string variable is an object, not a primitive type (in a way).
To add to Walter's comment. Which syntax is better is always subjective. It reflects the way of thinking. Taking backward, it also have influence on how a programmer thinks after getting used to the syntax.

When thinking about solving a problem, you do it differently based on complexity of the problem and based also on your previous experience.

Python is a hybrid language. That is, it supports syntax for plain functions (like len(var), structured programming, procedural, imperative), and also syntax "natural" for Object Oriented Programming (like var.upper()).

Often, the built-in functions call the related method of the object. For example len(s) calls s.__len__() (double underscores). The level of indirection makes the code more readable sometimes.

Syntax is about readability and about conversion of abstract ideas into a description in a form of a source code -- and vice versa.

Author

Commented:
Hi Walter and pepr,

I'm starting to get it :)

I program Windows batch files.  This is my fist efforts in object oriented programming.

Thanks guys for helping :)

Cheers,
Rene
Hi Rene,

In my opinion, Python is an extremely good replacement for the Windows batch files. You may choose another one occasionally--based on requirements--but you will probably not regret the decision to learn Python.

Have a nice day,
Petr

Author

Commented:
Thanks pepr,
Until next time :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial