Page 308 - Computer Science Class 11 With Functions
P. 308

Next, let us consider a more interesting piece of code:

          01 s = 'abcdefghij'     #Initial s
          02 print('id(s):', id(s), 's:', s)
          03 for ch in s:
          04     s = s + ch
          05     print('id(s):', id(s), 's:', s)
          06 print('id(s):', id(s), 's:', s) # Final s
        The above code yielded the following output on execution:

        id(s): 1631127023152 s: abcdefghij
        id(s): 1631126713008 s: abcdefghija

        id(s): 1631126713008 s: abcdefghijab
        id(s): 1631126713008 s: abcdefghijabc
        id(s): 1631126713008 s: abcdefghijabcd
        id(s): 1631126713008 s: abcdefghijabcde

        id(s): 1631127097456 s: abcdefghijabcdef
        id(s): 1631127097456 s: abcdefghijabcdefg
        id(s): 1631127097456 s: abcdefghijabcdefgh
        id(s): 1631127097456 s: abcdefghijabcdefghi
        id(s): 1631127097456 s: abcdefghijabcdefghij

        id(s): 1631127097456 s: abcdefghijabcdefghij
        Note that even though the variable s finally denotes the string abcdefghijabcdefghij, the control exits the
        for-loop on processing the characters of the initial string s: abcdefghij. Also, note that when a string object has

        outlived its purpose, Python may not create a new object id for another string object. Thus, the strings, 'abcdefghij',
        'abcdefghijab', 'abcdefghijabc', 'abcdefghijabcd', and 'abcdefghijabcde' have the same
        object id. However, it is not a general rule, and the strings 'abcdefghijabcde' and 'abcdefghijabcdef'
        have different object ids. As a general rule, we should avoid such obfuscated codes.



               Never modify the value of a control variable inside a for-loop.



        12.1.9 Transforming Numerical Values to Strings
        A numerical value may be transformed into a string using the str() function. For example,

         >>> 'I want' + str(2) + 'cups of ice cream.'
              'I want 2 cups of ice cream.'


               Membership operator in: Examine the membership of a particular character or a substring in the given string using
               the membership operator in.
               str(): To transform a data object to a string


        12.2 String Slices


        Often, we are interested in extracting/accessing more than one character, i.e. a subsequence of characters from the
        string. For example, we may be looking for the last name of an employee, or we may be interested in a name beginning
        with Abhishek. A subsequence of characters in a string is called a slice. A slice is marked by specifying the start and
        finish indices using the notation: <start>:<finish>.

         306   Touchpad Computer Science-XI
   303   304   305   306   307   308   309   310   311   312   313