String Methods count s ITH JFK ITH m scount ITH T H I T I F J K H s 0 1 2 3 4 5

# String methods count s ith jfk ith m scount ith t h i

This preview shows page 9 - 20 out of 39 pages.

String Methods: count >>> s =‘ITH -JFK- ITH’ >>> m = s.count (‘ITH’) T H I T I F J K - H - s --> 0 1 2 3 4 5 6 7 8 9 10 m --> 2 s1.count(s2) the number of occurrences of string s2 in string s1 String Methods: count >>> s =‘ITH -JFK- ITH’ >>> m = s.count (‘LGA’) T H I T I F J K - H - s --> 0 1 2 3 4 5 6 7 8 9 10 m --> 0 s1.count(s2) the number of occurrences of string s2 in string s1 count The Formal Definition If s1 and s2 are strings, then s1.count(s2) returns an int value that is the number of occurrences of string s2 in string s1. Note, in general s1.count(s2) is not the same as s2.count(s1) Using count : An Example # Count the number of vowels… A = ‘ auric goldfinger n = 0 n = n + A.count (‘a’) n = n + A.count (‘e’) n = n + A.count (‘ i ’) n = n + A.count (‘o’) n = n + A.count (‘u’) print n Illegal: n = A.count (‘a’ or ‘e’ or ‘I’ or ‘o’ or ‘u’) Designing find as a Function find Where is the first occurrence of string y in a string x ? find ‘ITH -JFK- ITH’ - 3 It would then be used like this: n = find(y,x) Designing find as a Method >>> s =‘ITH -JFK- ITH’ >>> idx = s.find (‘JFK’) T H I T I F J K - H - s --> 0 1 2 3 4 5 6 7 8 9 10 idx --> 4 s1.index(s2) the index of the first occurrence of string s2 in string s1 String Methods: find >>> s =‘ITH -JFK- ITH’ >>> idx = s.find (‘RFK’) T H I T I F J K - H - s --> 0 1 2 3 4 5 6 7 8 9 10 idx --> -1 s1.index(s2) evaluates to -1 if there is no occurrence of s2 in s1 find The Formal Definition If s1 and s2 are strings, then s1.find(s2) returns an int value that is the index of the first occurrence of string s2 in string s1. If there is no such occurrence, then the value -1 is returned. Using find : Some Examples s = ‘nine one one n1 = s.find (‘one’) n2 = s.find (‘two’) n3 = s.find (‘ nine’) -1 n2 -> 5 n1 -> n3 -> -1 in : A Handy Boolean Device If s1 and s2 are strings, then s1 in s2 is a boolean-valued expression. True if there is an instance of s1 in s2 . False if there is NOT an instance of s1 in s2 .   #### You've reached the end of your free preview.

Want to read all 39 pages?

• Fall '19
• Irrational number, Square number, Replacements
• • • 