
|
Lesson 10 Notes: String Things
- The Things in Strings
- Strings are actually made up of smaller units, each individual character.
- Each character has an address number within the string, with the first character being number zero (0).
- Each individual character, or set of characters, in a string can be accessed using their address number.
- Bits of String
- Use [ ] to access characters in a string.
- Example:
word = "computer"
letter = word[0]
- More Bits of String
- Use [ # :#] to get set of letters
part = word[0:3]
- To pick from beginning to a set point:
part = [:4]
- To pick from set point to end:
part = [3:]
- To pick starting from the end:
part = [-1]
- How Long is the String
- Find out how many characters are in a string by using the len() function.
- The len() function requires a string as an argument.
- Example
word = "computer"
length = len(word)
- Walking Through a String
- May want to do a test on a string one letter at a time. Two ways to do this: while or for loop.
- while loop:
index = 0
while index < len(word):
letter = word[index]
print letter
index=index +1
- For Loop
- Shorter way to write that same "while" loop is with a "for" loop.
- Example:
word = "computer"
for letter in word:
print letter
- Note that we made up the variable "letter" when we created the for loop.
- Useful "for" loop
- Sample Program:
# Vowel counting program
word = raw_input("Enter a word")
vowels = "aeiouy"
count = 0
for letter in word:
if letter in vowels:
count = count+1
else:
pass
print "Number of vowels =", count
- Comparing Strings
- Strings can be used in comparison tests.
- Example:
if word < "cebu":
print word
- According to Python, all uppercase letters come before lowercase letters when comparing. (so Z > a).
- Good idea to convert to same case before comparing.
- String Module
- The string module contains a number of useful functions including:
- lower()
- upper()
- find()
- count()
- See documentation for more functions and uses.
- Review
- What code is used to access parts of a string?
- What function finds the number of characters in a string?
- How is a "for" loop written?
- What are the guidelines for comparing strings?
Restricted access |