Last time we learned the important fact that strings are immutable; once created a string value cannot be changed. Strings are also objects in Python meaning that they have methods (i.e., functions) that can be used to operate on them. Today, we’ll look at methods to test the value of strings, perform various “modifications”, and search/replace substrings within a string.
Testing Methods
Testing methods all return a Boolean (True or False) result based on some test, they do not change the value of the original string in any way. Below is a summary of common testing methods:
Here is an example to demonstrate these methods in action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
userString = input('Enter a string: ') print('This is what I found about that string:') if userString.isalnum(): print('The string is alphanumeric.') if userString.isdigit(): print('The string contains only digits.') if userString.isalpha(): print('The string contains only alphabetic characters.') if userString.isspace(): print('The string contains only whitespace characters.') if userString.islower(): print('The letters in the string are all lowercase.') if userString.isupper(): print('The letters in the string are all uppercase.') print('userString is unchanged:', userString) |
“Modification” Methods
Although strings are immutable, they have methods that return a modified copy of themselves. Below is a summary of these methods:
Here’s an example to demonstrate some of these methods:
1 2 3 4 5 6 7 8 |
userName = input("Please tell me your name: ") print("I will shout your name: ", userName.upper()) print("Now all in lowercase: ", userName.lower()) print("How about inverting the case? ", userName.swapcase()) print("Your name has not really changed, see: ", userName) userName = userName.upper() print("Now we've actually changed it: ", userName) |
Again, none of these methods actually change the original string value. Line 7 demonstrates how to make a variable refer to a new (modified) copy of a string value.
Search and Replace Methods
Programs often need to search for substrings or strings that appear within other strings. Here is a summary of these:
And an example…
1 2 3 4 5 6 7 |
userName = input("Please tell me your name: ") print("Now I'll pronounce your name like a cartoon character:") userName = userName.upper() userName = userName.replace("R", "W") userName = userName.title() print(userName) |
Whew, that’s a lot of methods! I hope you don’t feel overwhelmed by all of this. Don’t worry if you forget how some of these methods work, you can always look up the details in the online help using the help(str) command. The main thing is to have an idea of the kinds of methods that are available so you’ll know what to look for when the time comes, and avoid creating a method that already exists.
The most important fact about string methods is that they do not modify the original string object they are called with, the best they can do is return a copy of the string. This makes sense because we know that strings are immutable.
You Try!
-
- Start a new page in your Learning Journal titled “3-5 String Methods“. Carefully read the notes above and in your own words summarize the key ideas from each section.
- Try to figure out what the following code will display, then check your hypothesis using the Python interpreter.
123ch1 = 'a'ch2 = ch1.upper()print(ch1, ch2) - Try to figure out what the following code will display, then check your hypothesis using the Python interpreter.
123text = 'CA$H M0NEY!'print(text.lower())print(text) - Using string methods, write 1 line of code for each of the following:
-
-
- Capitalize “python”.
-
-
-
- Find the first occurrence of “2” in “CO2 H2O”.
-
-
-
- Determine whether “Python” begins with lowercase or not.
-
-
-
- Determine whether “http://www.vik-20.com” ends with “.com” or not.
-
-
-
- Convert “PyThOn” to lowercase letters and then capitalize the result.
-
-
-
- Remove the leading and trailing whitespace from ” \n Python \nRules \t “.
-
-
- Extra Challenge: Write a function called word_jumble() that accepts a one-word string from the user. The function should create and return a new string that contains all of the same letters of the parameter string but in random order. For example, word_jumble(“Hello”) might return “lelHo”or “elHlo” etc.. Write a main() function to demonstrate how it works.