An Introduction To Python - Processing Strings
-
Upload
blue-elephant-consulting -
Category
Education
-
view
68 -
download
3
Transcript of An Introduction To Python - Processing Strings
An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #13:
Processing Strings
Processing Strings
• One of the main usages of loops is to process strings.
• Examples:
– Count the occurrence of one or more characters in a string
– Verify that the contents of a string meet a criteria
• All of this requires basic string processing algorithms
4 String Processing Methods
• variable.isupper– Test to see if current character is upper case
– Returns True or False
• variable.islower– Test to see if current character is lower case
– Returns True or False
• variable.upper– Converts current character to upper case
• variable.lower– Converts current character to lower case
Counting Matches
• We often want to count the number of values that meet a given condition.
• Example: count the number of upper case characters in a string
uppercase = 0for char in string :
if char.isupper() :uppercase =uppercase + 1
• Sometimes, you need to count the number of occurrences of multiple characterswithin a string.
• Example, suppose we would like to know how many vowels arecontained in a word.
vowels = 0for char in word :
if char.lower() in "aeiou" :
vowels = vowels + 1
a & b
Note: using “.lower” allows us to limit the
number of characters that must be specified
in the literal string
Finding All Matches
• You may need to find the position of each match within a string. For example, suppose you are asked to print the position of each uppercase letter in a sentence.
• You cannot use the for statement that iterates over all characters because you need to know the positions of the matches. Instead, iterate over the positions (using for with range) and look up the character at each position:
sentence = input("Enter a sentence: ")for i in range(len(sentence)) :
if sentence[i].isupper() :print(i)
What We Covered Today
1. Tables
1. Creating
2. Accessing
3. Neighbors
4. Summing
2. List Algorithms
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. Lists, List algorithms
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/