Skip to article frontmatterSkip to article content

Chapter 2.3 - String Methods

High-level programming languages like Python include many features that greatly simplify common coding tasks. Some of these features are provided in the form of methods or functions. Built-in or “out of the box” methods and functions organize basic Python syntax and data types into commonly used algorithms. These algorithms are already coded for you. Your main task then is to learn how to use these features effectively. In the case of strings, there are many methods that strings already have before you even write a single line of code.

Assume that you have written the following code to define a string:

a = "Hello there"

Some examples of using methods for the variable a include:

a.upper()

Changes all characters in your string to uppercase: HELLO THERE

a.lower()

Changes all characters in your string to lowercase: hello there

a.title()

Creates a string with the first letter of each word capitalized: Hello There

In Python, data types have specific functionality that is either implicit or explicit:

  • Implicit “Operations”:

    • Example: “add the integer 1 to the integer 1”
    • 1 + 1
    • Output: 2
    • Obvious and basic expectations for the data type
  • Explicit “Methods”:

    • Example: “convert every character to upper case”
    • "lower".upper()
    • Output: ‘LOWER’
    • Not obvious and not a basic expectation for the data type

There is no symbol that would be obvious for converting all characters to upper case, so a method was created that all strings can use named upper().

Chapter 2.3.1 - Basic string function syntax

The first requirement is that you define a str data type

a = "TEST"

print(a)
TEST

Next, you must use “dot notation” to tell Python you intend to use a string method:

a.

Immediately after the “dot”, you must provide an existing method name. To find all possible method names, you can use the dir() command. This is sometimes useful for quick reminders, but does not tell us much about the method itself.

dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Say that we want to use a method that turns all characters into lower case. We can look at the output above and guess that ‘lower’ is a method that does just that.

We then add that name, exactly as it appears, after the variable name:

a.lower

If we stop here, we will get the following output:

a.lower
<function str.lower()>

The output from that code is the function (method) itself. We can examine this using the help() command to see if it does what we want it to do.

help(a.lower)
Help on built-in function lower:

lower() method of builtins.str instance
    Return a copy of the string converted to lowercase.

We need one more step to “run” the function.

To run the function, you must add open and closed parentheses:

a.lower()
a.lower()
'test'

Since we know the rules of setting variables, we also know that anything on the right side of an equation is evaluated first, and can be set equal to a variable:

b = a.lower()

print(b)
test

Chapter 2.3.2 - Parameters

For some string methods, you are required to provide parameters.

Parameters:

values that are used by the method to follow specific behavior needed for the task

Example:

Parameters x and y can be modified to control the result of this mathematical function: F(x,y)F(x, y) = x2^{2} + y2^{2}

We can create a Python function that is equivalent to the equation above. We will learn all about how to create our own functions later in the class. Try changing x and y to see how that modifies the result.

def F(x, y):
    return x**2 + y**2

x = 2
y = 2

print("x =", x, "y =", y)
print("F(x, y) =", F(2,2))
x = 2 y = 2
F(x, y) = 8

Example of using parameters: the split() function.

If we run the help() command on split(), we get the following description:

help(b.split)
Help on built-in function split:

split(sep=None, maxsplit=-1) method of builtins.str instance
    Return a list of the substrings in the string, using sep as the separator string.

      sep
        The separator used to split the string.

        When set to None (the default value), will split on any whitespace
        character (including \n \r \t \f and spaces) and will discard
        empty strings from the result.
      maxsplit
        Maximum number of splits.
        -1 (the default value) means no limit.

    Splitting starts at the front of the string and works to the end.

    Note, str.split() is mainly useful for data that has been intentionally
    delimited.  With natural text that includes punctuation, consider using
    the regular expression module.

This time, help not only describes what the method does (return a list of the words in the string, using sep as the delimiter string.), but it also describes each method parameter.

In this case, the sep parameter is used as a delimiter which splits the string into subsets.

For example, split the following into sentences:

c = "The happy husky barked. The husky then jumped."

c.split(".")
['The happy husky barked', ' The husky then jumped', '']

Chapter 2.3.3 - Practice using string methods

Using this website: https://www.w3schools.com/python/python_ref_string.asp

Find and properly use string methods that can answer the following questions based on the given string definition. Use the help command or documentation on the website to determine how you can use these methods.

d = "The temperature is 20 F, the dewpoint is 15 F"

print(d)
The temperature is 20 F, the dewpoint is 15 F
  1. Are all of the characters alphabetical?
  1. At what position (index) does the substring “temperature” begin?
  1. What are the two halves of the string if you use a comma to split them?
  1. Does the string start with “The”?
  1. How many times does the letter “e” show up in the string?