Because strings are object, every string instance has its own attributes and methods. The most important attribute of the string is the collection of characters. There is a wide variety of methods. Try the following program.
In this example, upper is a method that can be invoked on any string object to create a new string in which all the alphabetic characters are in uppercase. lower works in a similar fashion, changing all alphabetic characters in the string to lowercase. (The original string message remains unchanged. A new string is created and assigned to lower_message.)
In addition to upper and lower, the following table provides a summary of some other useful string methods. There are a few activecode examples that follow so that you can try them out.
Table7.8.1.
Method
Parameters
Description
upper
none
Returns a string in all uppercase
lower
none
Returns a string in all lowercase
capitalize
none
Returns a string with first character capitalized, the rest lower
strip
none
Returns a string with the leading and trailing whitespace removed
lstrip
none
Returns a string with the leading whitespace removed
rstrip
none
Returns a string with the trailing whitespace removed
count
item
Returns the number of occurrences of item
replace
old, new
Replaces all occurrences of old substring with new
center
width
Returns a string centered in a field of width spaces
ljust
width
Returns a string left justified in a field of width spaces
rjust
width
Returns a string right justified in a field of width spaces
find
item
Returns the leftmost index where the substring item is found, or -1 if not found
rfind
item
Returns the rightmost index where the substring item is found, or -1 if not found
index
item
Like find except causes a runtime error if item is not found
rindex
item
Like rfind except causes a runtime error if item is not found
You should experiment with these methods so that you understand what they do. Note once again that the methods that return strings do not change the original. You can also consult the Python documentation for strings 1 .
Checkpoint7.8.2.
What is printed by the following statements?
s = "python rocks"
print(s.count("o") + s.count("p"))
0
There are definitely o and p characters.
2
There are 2 o characters but what about p?
3
Yes, add the number of o characters and the number of p characters.
Checkpoint7.8.3.
What is printed by the following statements?
s = "python rocks"
print(s[1] * s.index("n"))
yyyyy
Yes, s[1] is y and the index of n is 5, so 5 y characters. It is important to realize that the index method has precedence over the repetition operator. Repetition is done last.
55555
Close. 5 is not repeated, it is the number of times to repeat.
n
This expression uses the index of n
Error, you cannot combine all those things together.
This is fine, the repetition operator used the result of indexing and the index method.