String length ... len(str)
Jay O'Connor
joconnor at cybermesa.com
Wed Dec 3 19:15:16 EST 2003
Jeff Wagner wrote:
>Can someone please explain the following to me:
>
>
>
>>>>str1 = "here"
>>>>str2 = "here", "we", "are"
>>>>len(str1)
>>>>
>>>>
>4
>
>
>>>>len(str2)
>>>>
>>>>
>3
>
>Why is len(str1) = 4 and len(str2) = 3?
>
>If we were to say it's because the len() functions returns the number of elements in a string, then
>len(str1) should be = 1
>
>It's a little confusing.
>
>
str2 =is a tuple of three strings, not a concatenated string. So you
are getting the number if strings in the tuple, not the number of
characters in a longer string. You have to use join to concatenate the
strings with either join() or +
>>> str2 = "here", "we", "are"
>>>
>>> str2
('here', 'we', 'are')
>>> type (str2)
<type 'tuple'>
>>> len (''.join (str2))
9
>>> str3 = "here" + "we" +"are"
>>> str3
'hereweare'
>>> len (str3)
9
More information about the Python-list
mailing list