Lesson 5, Bit 3: String Methods

Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object.

Python has a function called dir which lists the methods available for an object. The type function shows the type of an object and the dir function shows the available methods.

Code Result
stuff = 'Hello world'
type(stuff)
<type 'str'>
dir(stuff) ['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Calling a method is similar to calling a function—it takes arguments and returns a value—but the syntax is different. We call a method by appending the method name to the variable name using the period as a delimiter.  A method call is called an invocation; in this case, we would say that we are invoking upper on the word.

Instead of the function syntax action(word), it uses the method syntax word.action().

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.

Testing Methods

The testing methods test a string for a condition.  These methods are the ones which begin with the word "is" as though you are asking a question.  These methods always return a Boolean value - either True or False.  They are very useful in conditional statements and while loops.

The isalnum Method

The isalnum method returns True if all characters in the string are alphanumeric (letter and numbers) and there is at least one character in string. Returns False otherwise.

Code Result Notes
string = 'banana'
string.isalnum()
True

All characters in this string are letters and numbers, therefore isalnum() returns True.

word = 'Banana 5!'
word.isalnum()
False

The exclamation point and space are not alphanumeric characters, therefore isalnum() returns False.

The isalpha Method

The isalpha method returns True if all characters in the string are alphabetic and there is at least one character in the string, returns False otherwise.

Code Result Notes
string = 'banana'
string.isalpha()
True All characters in this string are letters, therefore isalpha() returns True.

word = 'Banana 5!'
word.isalpha()
False

The exclamation point, the space, and the number 5 are all not alphabetic characters.  Therefore isalpha() returns False.

The islower Method

The islower method returns True if all cased characters in the string are lowercase and there is at least one cased character in the string. Returns False otherwise.

Code Result Notes
string = 'banana'
string.islower()
True islower() returns True.

word = 'Banana 5!'
word.islower()
False

The capital B is not a lower case letter, therefore islower() returns False.

word = 'banana 5!'
word.islower()
True Even though there is a space, a number, and an exclamation point in the string, islower() only looks at characters which can be cased: letters. This time all letters are in lowercase.  Therefore, islower() returns True.

The isnumeric Method

The isnumeric method returns True if there are only numeric characters in the string.  Returns False otherwise.  Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

It should be noted that this does not check whether a string can be converted into a number using int() or float().  It only checks for Unicode values within the string.  This can be confusing.

Code Result Notes
string = 'banana'
string.isnumeric()
False

All characters in this string are letters, therefore isnumeric() returns False.

answer = '42'
answer.isnumeric()
True

All characters are numbers, therefore isnumeric() returns True.

answer = '42.5'
answer.isnumeric()
False

While we consider 42.5 to be a number, the period is not considered to be a numeral in Unicode.  Therefore isnumeric() returns False.

The isspace Method

The isspace method returns True if all characters in the string are whitespace and there is at least one character in the string. Returns False otherwise.

Code Result Notes
string = 'banana'
string.isspace()
False

All characters in this string are letters, therefore isspace() returns False.

word = 'Banana 5!'
word.isspace()
False

While there is a space in this string, there are non-space characters too.  Therefore isspace() returns False.

space = ' '
space.isspace()
True

The only character in this string is a space, therefore isspace() returns True.

The istitle Method

The isstitle method returns True if the string is a title-cased string and there is at least one character in the string, i.e. upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones. Method returns False otherwise.

Code Result Notes
string = 'banana'
string.istitle()
False

The one word in this string begins with a lowercase letter, therefore istitle() returns False.

word = 'Banana 5!'
word.istitle()
True

The only cased word in this string is Banana which starts with an upper case.  Therefore istitle() returns True.

word = 'Banana pie'
word.istitle()
False

There are two cased words in this string, but only one of them begins with a capital letter.  Therefore istitle() returns False.

The isupper Method

The isupper method returns True if all cased characters in the string are uppercase and there is at least one cased character in the string. Returns False otherwise.

Code Result Notes
string = 'banana'
string.isupper()
False

The only cased word in this string is banana which is in all lower case.  Therefore isupper() returns False.

word = 'BANANA 5!'
word.isupper()
True

The only cased word in this string is BANANA which is in all upper case.  Therefore isupper() returns True.

Launch Exercise

Manipulation Methods

The remaining methods which are available to the str object make changes to the string.  In other words, they manipulate the string.  It should be noted that we are not permanently replacing the string.  When each method is invoked, we are making a COPY of that string and leaving the original string alone.

The upper Method

The method upper takes a string and returns a new string with all uppercase letters:

Code Result
word = 'banana'
word.upper()
BANANA

In this example, word.upper() is a copy of word.  If we were to display the value of word, we would see that it is still the same as it was before we invoked the upper method:

Code Output
word = 'banana'
word.upper()

print(word.upper())

print(word)
BANANA
banana

See? The variable word is left untouched. This is true for all of these methods.

The lower Method

The lower method will take a string and return a new string with all lowercase letters:

Code Output
word = 'bAnaNa'
new_word = word.lower()
print(new_word)
banana

The capitalize Method

The captialize method will take a string and return a new string with the first character capitalized and the remaining letters in lowercase.  If the first character is not a letter, then the string is returned in lowercase:

Code Output
word = 'bAnaNa'
new_word = word.capitalize()
print(new_word)
Banana
word = '#1 bAnaNa'
new_word = word.capitalize()
print(new_word)
#1 banana

The strip Method

One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the strip method. 

Note: I have included quotes around the string to show the white space in the output.

Code Output
line = ' Here we go '
new_line = line.strip()
print(new_line)
'Here we go'

The lstrip Method

Only want to remove white space from the left side of the string?  Use the lstrip method.

Note: I have included quotes around the string to show the white space in the output.

Code Output
line = ' Here we go '
new_line = line.lstrip()
print(new_line)
'Here we go '

The rstrip Method

Only want to remove white space from the right side of the string?  Use the rstrip method.

Note: I have included quotes around the string to show the white space in the output.

Code Output
line = ' Here we go '
new_line = line.rstrip()
print(new_line)
' Here we go'

Launch Exercise