Page 262 - Computer Science Class 11 Without Functions
P. 262

C T  01
                      1.  Write a program that accepts a string from the user and prints its reverse.
                      2.  Rewrite the program mentioned in task 1 using negative indices.



        11.2 Membership Operator in
        We may examine the membership of a particular character or a substring in a given string using the membership
        operator  in.  The  expression  <subStr> in <string1> returns  True or  False  depending  on  whether  the
        string <subStr> is a substring of <string1>. For instance, in the following examples, 'h' is present in the string
        'hello'; however, 'H' is not found in the string 'hello'.
         >>> 'h' in 'Hello'
              False
         >>> 'h' in 'hello'
              True
         >>> 'ing' in 'playing'
              True
        The last expression returns True as the string 'ing' is the part of the string 'playing'.

        Let us write a program that counts the number of digits in a string. For this purpose, we initialize the digit count
        (digitCount) as zero and increment it by one every time a character of the input string belongs to the string

        '0123456789'.
          01 '''
          02 Objective: To count the number of digits in a string.
          03 Input: txt - string
          04 Output: number of digits in string txt
          05 '''
          06
          07 txt = 'Hello 123 hello 123'
          08
          09 digits = '0123456789'
          10 digitCount = 0
          11 for ch in txt:
          12     if ch in digits:
          13         digitCount +=1
          14
          15 print('No. of digits in \''+ txt + '\': ', digitCount)
        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

         260   Touchpad Computer Science-XI
   257   258   259   260   261   262   263   264   265   266   267