Execute Program

Python for Programmers: More String Methods

Welcome to the More String Methods lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We've seen a few string methods already. This lesson will cover some more common string methods.

  • .upper converts the entire string to uppercase.

  • >
    "Amir".upper()
    Result:
    'AMIR'Pass Icon
  • .lower converts it to lowercase.

  • >
    "Amir".lower()
    Result:
    'amir'Pass Icon
  • The .split method splits a string by a given separator. It gives us a list of the strings that occur between the separators.

  • >
    "a,b,c".split(",")
    Result:
  • >
    "a:b".split(":")
    Result:
    ['a', 'b']Pass Icon
  • If the string doesn't contain the separator, .split returns a list with the original string.

  • >
    "a,b,c".split("%")
    Result:
    ['a,b,c']Pass Icon
  • The separator can be multiple characters. Python only breaks the string in places where the entire separator appears together.

  • >
    "a, b, c".split(", ")
    Result:
    ['a', 'b', 'c']Pass Icon
  • It's easy to make mistakes in the separator string. For example, our string might be "a, b, c". If we split on just ",", then our list will include the spaces in its strings.

  • >
    "a, b, c".split(",")
    Result:
  • If the string starts with the separator, we get an empty string "" as the first element.

  • >
    "$17$18".split("$")
    Result:
  • If the string ends with the separator, we get an empty string as the last element.

  • >
    "17.18.".split(".")
    Result:
    ['17', '18', '']Pass Icon
  • >
    ":abc:".split(":")
    Result:
    ['', 'abc', '']Pass Icon
  • .splitlines splits multi-line text into a list of lines, but we don't need to provide a separator. It handles newlines (\n), carriage returns (\r), and Windows-style line terminators (\r\n). This makes .splitlines work across different operating systems. Getting the same effect with .split would take a lot more work.

  • >
    "Amir\nBetty\r\nCindy".splitlines()
    Result:
    ['Amir', 'Betty', 'Cindy']Pass Icon
  • .join is the opposite of .split. It combines list elements into one string, inserting the provided string between the elements.

  • >
    cat_names = ["Keanu", "Ms. Fluff", "Wilford"]
    ", ".join(cat_names)
    Result:
  • >
    animal_names = ["cat", "dog", "owl"]
    ", ".join(animal_names)
    Result:
    'cat, dog, owl'Pass Icon
  • If we combine .join and .split, we get the list that we started with.

  • >
    cat_names = ["Keanu", "Ms. Fluff", "Wilford"]
    ", ".join(cat_names).split(", ")
    Result:
    ['Keanu', 'Ms. Fluff', 'Wilford']Pass Icon
  • .strip removes leading and trailing whitespace. That includes spaces, newlines (\n), line feeds (\r), tabs (\t), and some other less-common whitespace characters.

  • >
    " Hello, Amir\n".strip()
    Result:
    'Hello, Amir'Pass Icon
  • Without an argument, .strip removes whitespace, as shown above. But we can also provide a chars argument, which is the set of characters to remove. .strip will remove any of the characters we provide from the beginning and end of the string.

  • (Note that unlike .split, the characters don't have to occur together.)

  • >
    "!!!1000.!..".strip(".!")
    Result:
    '1000'Pass Icon
  • >
    "!10!00.".strip(".!")
    Result:
    '10!00'Pass Icon
  • We can replace a substring with .replace(old, new).

  • >
    "Hello, NAME".replace("NAME", "Amir")
    Result:
    'Hello, Amir'Pass Icon
  • .replace replaces all instances of the old string, not just the first one.

  • >
    "NAME,36,NAME".replace("NAME", "Amir")
    Result:
    'Amir,36,Amir'Pass Icon
  • Here's a code problem:

    Write a loop that takes a comma-separated string of integers like "1,2,3", .splits them into a list, then sums them together. As a reminder, int() converts strings into numbers.

    def sum_string(s):
    total = 0
    for value in s.split(","):
    total += int(value)
    return total
    assert sum_string("5,3,1,2,4") == 15
    assert sum_string("1,10,100,1000") == 1111
    assert sum_string("0") == 0
    Goal:
    No errors.
    Yours:
    No errors.Pass Icon