And Now For Something Familiar -- Confusion


#1

This was the answer for this section that seems to be right:

my_string = "hey"
print len(my_string)
print my_string.upper()

However, I’m trying to understand why print my_string.len() wouldn’t work.

Strings and Console Output


#2

You are not alone in your confusion. There is a typo in the instructions. As it stands, there is no str.len() method, only the built in len(iterable).

Addendum

Objects that are iterable, and that are valid arguments for the len() function:

>>> _ = {}
>>> len(_)
0
>>> _['a'] = 1
>>> len(_)
1
>>> _ = []
>>> len(_)
0
>>> _ += [1]
>>> len(_)
1
>>> _ = (1,2,3)
>>> len(_)
3
>>> _ = ""
>>> len(_)
0
>>> _ = "123"
>>> len(_)
3
>>> _ = (1)
>>> len(_)

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    len(_)
TypeError: object of type 'int' has no len()
>>> 

(1) is interpreted as just, 1. Tuples have a length of two or more. That’s why we can write,

 print "Temperature outside right now is %d Celsius degrees" % 5

but we cannot write,

 print "The were %d %s on the telephone wire, today." % 'three', 'gray doves'

Multiple arguments must be written in a tuple.

 print "The were %d %s on the telephone wire, today." % ('three', 'gray doves')

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.