There are many built-in string methods in Python. We will cover a few of them here, and all of them in a future article. A method saves the programmer from having to program the same code over and over again. Instead of typing a bunch of code to say, count the number of a's in a string, all the programmer has to do is call the appropriate method. In the following example, we are going to find out how many times each vowel appears in a string. Type the following into your python shell command prompt: book='It was a dark and stormy night, the wind blowing through the trees, and somewhere, out there in the far off teinkling of city lights, Britney Spears was busy being a bad mother...' book.count('a') book.count('e') book.count('i') book.count('o') book.count('u') book.count('y') The method will count each of the vowels and return a result, like the one below: >>> book.count('a') 10 >>> book.count('e') 15 >>> book.count('i') 10 >>> book.count('o') 8 >>> book.count('u') 3 >>> book.count('y') 4 We can also count words within the document, like so: >>> book.count('the') 5 >>> book.count('and') 2 >>> book.count('was') 2
blog comments powered by Disqus |
|
|
|
|
|
|
|