Over time, programmers have found themselves doing the same operations on string data over and over again. Python contains a useful set of string functions to help you do these tasks without re-inventing the same code within your program.

You have already worked with one powerful string function - str.format() - which lets you produce nicely formatted output messages using a format string and other input data. In this lesson, we will explore some of the other functions that belong to the string object.

Calling String Functions - 3 Ways
There are at least three ways you can call Python's string functions! You have already seen one approach when we described how to call the string's format() function as follows:

str.format(<format string>,<other parameters>) # general format
result = str.format("Your change is ${:.2f}",5.25) # specific example
Copy
With this approach, you write "str." at the beginning, followed by the function name. The first parameter inside the parentheses is always the format string value on which you want to do some work. Afterward, you can add any remaining parameters that the format string requires.

If your target string is stored in a string variable, then you can instead call the function using the variable name instead of "str" at the beginning. In the example below, we store the format string in the myChange variable, then call format() directly on that variable.

myChange = "Your change is ${:.2f}" # store format string in variable first
result = myChange.format(5.25) # call format() using string variable
Copy
With this approach, you do not need to pass in the main string value as the first parameter. The function will automatically use the value stored in the variable as the main string value.

One last approach lets you call the string function directly on a hard-coded string value, without storing it in a variable first.

result = "Your change is ${:.2f}".format(5.25) # call format() using hard-coded string
Copy
In summary, you can call any string function using "str." at the beginning, and pass in a string value or variable as the first parameter. Or, you can call any string function using a string variable name or a hard-coded string at the beginning, and just pass in any additional parameters that the function may require.

In our lessons, we will generally use the first approach with "str." placed before the function name. This makes it obvious we are calling a string function. However, all approaches work equally well and you may see them in code written by others.
To convince yourself that each of the three ways to call string functions work as described, study the code below. We have demonstrated each approach using a string function called count(). This function will search the main string and count how many times a smaller string is found within the larger string. So, str.count("Hello","l") will return 2, because the lowercase "L" letter appears twice in that word.

Run the code yourself to see the results. We are counting the number of times the string "s" appears in bigWord, and count() should find it 3 times.

Try It Now


Searching Strings
Programs will often want to closely examine string data to see if the overall value contains shorter or smaller pieces (also called substrings). For example, you might ask the user to enter a name and they respond with a value that includes a prefix like "Mr.", "Mrs.", "Miss" or a suffix like "Jr.", "II". How would you figure out that an input like "Mr. Davey Jones II" contains the substring "Mr." on the front or "II" on the end?

Python contains several string functions that can be used to search a larger string for a smaller substring.

Function Description
str.count(<string>,<substring>) Returns an integer number of times that substring is found in the larger string.
str.startswith(<string>,<substring>) Returns True if the substring is found at the beginning of the string, or False otherwise.
str.endswith(<string>,<substring>) Returns True if the substring is found at the end of the string, or False otherwise.
str.find(<string>,<substring>) Returns the numeric index of the first position of the substring found in the larger string. If substring is not found, -1 is returned.
str.index(<string>,<substring>) Returns the numeric index of the first position of the substring found in the larger string. If substring is not found, a run-time exception will occur.
Use the example code below to experiment with each of these functions. Can you predict the output in each case?

Try It Now


Notice what happens on the last line when calling str.index(). Because the target substring is not found, an exception will be thrown, which completely halts the program. If you are not confident the target substring will be found, use str.find() instead. str.find() will return -1 when the substring is not found, and your program can continue running.

count("B") = 3
find("pp") = 2
find("bb") = -1
startswith("Bip") = True
endswith("Boo") = True
Traceback (most recent call last):
File "code1.py", line 8, in
print("index(\"bb\") =",str.index(rhyme,"bb")) # "bb" not present, so will throw exception
ValueError: substring not found
Python supports one additional way you can quickly check for the presence of a substring inside a larger string. Instead of calling a string function, you can use the "in" keyword instead. Use "in" when you want to just get a quick True or False answer and are not worried about the actual position of the substring within the larger string.

The expression "<substring> in <string>" will return True if the substring is found anywhere inside the string, or False otherwise. Similarly, the expression "<substring> not in <string>" will do the exact opposite, returning True if the substring is not found.

Run the code below to see the "in" and "not in" logical expressions at work!

Try It Now


Remember that the characters (\") found inside a string is an escape sequence that results in a single double-quote (") appearing at that location. You should now be familiar with escape sequences, and we'll be using them frequently to produce nicely formatted output.

Modifying Strings
Sometimes, you will find that a string is not in exactly the right format, and you will want to make some modifications to the string value. As you know, string values are immutable, which means the original string can't be changed. However, Python contains several functions that will create a new string based on the original string contents.

Function Description
str.capitalize(<string>) Returns a new string with the first character in the string capitalized and the remaining characters changed to lower case.
str.lower(<string>) Returns a new string with all lowercase letters.
str.upper(<string>) Returns a new string with all uppercase letters.
str.replace(<string>,<old substring>, <new substring>) Returns a new string where all occurrences of the old substring are replaced by the new substring.
str.split(<string>,<separator>) Returns a list of individual words or items in the string. See below for details!
str.strip(<string>) Returns a new string with all white space characters (spaces, tabs, etc) removed from the front and end of the string.
The capitalize(), lower(), upper() and strip() functions are very straight-forward. Use the sample code below to practice converting an input string into different cases and removing white space from both ends of a string.

Try It Now


Notice that the str.capitalize() function will only try to capitalize the first character, and if the first character is not a letter, that character will not be changed. In the code above, remove the two spaces at the front of the original string to make "i" the first character. Then, re-run the code to see the first "I" letter capitalized.

The replace() function is a great way to swap out all occurrences of one character or substring with another. Try running the code below to see how it works. Can you modify the code to produce the string "Yebbe Debbe Do!" ?

Try It Now


The split() function is a valuable tool for data processing. Given some long input string, split() will return a list of the individual words or data fields within the string. By default, whitespace characters like spaces are treated as separators, so using split() on a regular sentence will return a list of the words in the sentence. Consider the following code, which splits a quote by Julius Caesar:

quote = "Experience is the teacher of all things. - Julius Caesar"
print(str.split(quote))

Copy
split() will return the following list:

['Experience', 'is', 'the', 'teacher', 'of', 'all', 'things.', '-', 'Julius', 'Caesar']
split() has a second, optional parameter that lets you change the separator. You can split() on any character or substring. The example below uses the "-" character to split the quote instead of whitespace.

quote = "Experience is the teacher of all things. - Julius Caesar"
print(str.split(quote,"-"))

Copy
Because there is only one "-" character in the quote, split() will create a list with just two substrings.

['Experience is the teacher of all things. ', ' Julius Caesar']
Can you add a third split() statement to the example below? Try printing out the results when you split on the character "e".

Try It Now


Notice that the separator character (in this case, 'e') is not present in the output list at all. The separator character itself is discarded, and you just get the text between each separator.

['Exp', 'ri', 'nc', ' is th', ' t', 'ach', 'r of all things. - Julius Ca', 'sar']
String Slices
In Python, it is easy to pull out a smaller piece of a string. These smaller pieces of text found within larger strings are called substrings in most programming languages. In Python, a substring is also called a slice. Selecting a slice is similar to selecting a character with numeric index values and square brackets. But, instead of using a single numeric value, you use a range like [0:2] instead! The starting index is placed to the left of the colon and the ending index to the right. The actual slice will not include the character at the ending index, so that value should be one greater than the last character you want to grab.

If you leave out the first number (before the colon), the slice will start at the beginning of the string. If you leave out the last number (after the colon), the slice will continue until the end of the string. Try running the example below and observe the results. Can you change the first slice to get just the first "hop" substring?

Try It Now


Further Reading
Of course, Python has more advanced and powerful string functions that might be useful in your own programs. To read more about them, click on the link below to visit the official Python documentation.

1. What are three patterns that can be used to call the string functions?
2. Why pattern do we normally use in this course, and why?
3. Which functions allow you to search a larger string for a smaller part? What input parameters does each function take and what are the results?
4. How do you use "in" and "not in" to form a logical expression based on a string search?
5. Which functions produce some sort of modified output given some original string input? What input parameters does each function take and what are the results?
6. How do the string replace() and split() functions work?
7. How do you create a "slice" or substring from a larger string? What are the minimum and maximum possible values in the range?
8. What happens with slice() if you omit the index representing the lower or upper bound?

1. The three patterns that can be used to call string functions are:

a. Using "str." at the beginning followed by the function name and passing in the main string value and other parameters.
b. Storing the format string in a variable, then calling the function using the variable name and passing in any additional parameters.
c. Calling the string function directly on a hard-coded string value and passing in any additional parameters needed.

2. In this course, we normally use the pattern with "str." at the beginning before the function name. This is done to make it clear that we are working with string functions. However, all approaches work equally well.

3. The functions that allow you to search a larger string for a smaller part are:
a. str.count(<string>,<substring>): returns the number of times the substring is found in the larger string.
b. str.startswith(<string>,<substring>): returns True if the substring is found at the beginning of the string.
c. str.endswith(<string>,<substring>): returns True if the substring is found at the end of the string.
d. str.find(<string>,<substring>): returns the index of the first occurrence of the substring in the larger string (returns -1 if not found).
e. str.index(<string>,<substring>): returns the index of the first occurrence of the substring in the larger string (throws an exception if not found).

4. You can use the "in" keyword to quickly check for the presence of a substring inside a larger string.
For example: "<substring> in <string>" will return True if the substring is found, or False otherwise.
Similarly, "<substring> not in <string>" will return True if the substring is not found.

5. The functions that produce modified output given some original string input are:
a. str.capitalize(<string>): returns a new string with the first character capitalized.
b. str.lower(<string>): returns a new string with all lowercase letters.
c. str.upper(<string>): returns a new string with all uppercase letters.
d. str.replace(<string>,<old substring>, <new substring>): returns a new string with all occurrences of the old substring replaced by the new substring.
e. str.split(<string>,<separator>): returns a list of individual words/items in the string.
f. str.strip(<string>): returns a new string with all white space characters removed from the front and end of the string.

6. The replace() function replaces all occurrences of an old substring with a new substring in a string. The split() function splits a string into individual words/items based on a separator.

7. To create a slice or substring from a larger string, you use index ranges with square brackets. The minimum possible value is the starting index (inclusive), and the maximum possible value is the ending index (exclusive).

8. If you omit the index representing the lower bound in slice(), it will start at the beginning of the string. If you omit the index representing the upper bound, it will continue until the end of the string.