Page 307 - Computer Science Class 11 With Functions
P. 307
We begin by initializing the reverse string reverseStr as the null string and concatenating the characters in the
string str1 to the string reverseStr one by one, as shown below:
01 def reverse(str1):
02 '''
03 Objective: To reverse a string
04 Input Parameter: str1 - string
05 Return Value: reverse of str1 - string
06 '''
07 reverseStr = ''
08 for i in range(len(str1)):
09 reverseStr = str1[i] + reverseStr
10 return reverseStr
11 print(reverse('Hello'))
It is worth noting that in the definition of the function reverse(), for loop uses indexes 0, 1,..., length (n)-1. Thus,
when we invoke the function reverse, as reverse('Hello'), len('Hello') being 5, the variable i
takes values 0, 1, 2, 3, 4. On execution of the above program, Python responds with olleH as the output.
olleH
1. Write a program that accepts a string from the user and prints its reverse using the above function.
2. Rewrite the function reverse(str1) using negative indices.
12.1.8 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 function 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 def digitCount(s):
02 '''
03 Objective: To count the number of digits in a string.
04 inputs parameter: s: string
05 return value: number of digits in string s
06 '''
07 digits = '0123456789'
08 digitCount = 0
09 for ch in s:
10 if ch in digits:
11 digitCount +=1
12 return digitCount
13
14 txt = 'Hello 123 hello 123'
15 print('No. of digits in \''+ txt + '\': ', digitCount(txt))
Strings 305

