4.2. Strings are Objects¶
Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings. You use dot-notation to invoke the functions on a string object such as
sentence.lower(). The function
lower() returns a new string with all of the characters in the original string set to lowercase. The function
capitalize() will return a new string with the first letter of the string capitalized.
4.2.1. Getting Part of a String¶
A string has characters in a sequence. Each character is at a position or index which starts with 0 as shown below. An index is a number associated with a position in a collection of values like a string.
A slice is a way to get part of a string. One way to use a slice is to do stringName[num]`. This will return a new string with just the character at that position in the string.
A slice with two values separated with a
: between them returns a new string with the characters from the given start position to the one before the given end position.
Check Your Understanding
4.2.2. Some Other String Functions¶
len(string) function takes a string as input and returns the number of characters in the string including spaces.
find(string) function takes a string as input and returns the index where that string is found in the current string. If the string isn’t found it returns -1.
find function will return the first position it finds the given string in. Notice that above it printed 2 which means it found the “is” in “This” first.
Check your understanding
Write the code to evaluate the length of the string “I like green eggs” and print it. It should print “The length is 17”.
Create variable to hold the string.
Discuss topics in this section with classmates.