Reputation: 23
code1
if name.lower().endswith('b') and len(name) > 2
Suppose name is a type string
like name = "test_string"
So the name.lower().endswith('b')
is similar to name.lower() and endswith('b')
,
like then the alternate code of code1 will be:
code2
if name.lower() and name.endswith('b') and len(name) > 2
Are code1 and code2 the same?.
The doubt is what's the significance of code1? What's that nested ".
"? I really don't know. Is it like some sort of accessing technical feature in Python or any other programming language?
If so, which languages offer this concept?...
Upvotes: 0
Views: 45
Reputation: 1367
Consider an example:
name = "StackOverFLOW"
# Code 1
if name.lower().endswith('w'):
print("Passed Code 1")
# Code 2
if name.lower() and name.endswith('w'):
print("Passed Code 2")
The output for the above code is:
Passed Code 1
The reason for it can explain your query of using a period (.) in python which is more or less similar to the usage in other languages.
In Code 1, the name.lower()
returns stackoverflow
, and then it is again passed through a string method endswith('w')
which turns out to be True.
In Code 2, the name.lower()
returns stackoverflow
same as Code 1 but it is not passed through the endswith('w')
method. Instead there is another condition name.endswith('w')
which check if name
i.e. StackOverFLOW
ends with a lower case w
which is False
and hence, the condition breaks.
Upvotes: 1
Reputation: 780871
This is called method chaining.
x.method1().method2().method3()
is equivalent to
temp1 = x.method1()
temp2 = temp1.method2()
temp2.method3()
So
if name.lower().endswith('b') and len(name) > 2:
is equivalent to:
lowername = name.lower()
if lowername.endswith('b') and len(name) > 2:
It's not equivalent to
if name.lower() and name.endswith('b') and len(name) > 2:
because name.lower()
doesn't modify name
. So when you call name.endswith('b')
, name
still contains the original value, which could be uppercase.
If the value were a mutable type, the method could update it in place and return it. However, the general Python convention is that methods either update in place or they return a new object, they don't do both. That's why list.append()
returns None
, not the updated list, for instance. (Some functions update in place and then return a related value, e.g. list.pop()
removes an element from the list and returns the element.)
Upvotes: 1