String Methods

Case Methods

  1. # upper and lower
  2. "hello".upper()
  3. #ans: "HELLO"
  4. "HELLO".lower()
  5. #ans: "hello"
  6. "hello world".title()
  7. #ans: "Hello World"
  8. "hello".capitalize()
  9. #ans: "Hello"

Strip Methods

  1. # remove whitespace
  2. " hello ".strip()
  3. #ans: "hello"
  4. " hello ".lstrip()
  5. #ans: "hello "
  6. " hello ".rstrip()
  7. #ans: " hello"

Split

  1. # split string
  2. "apple,banana,cherry".split(",")
  3. #ans: ['apple', 'banana', 'cherry']
  4. "one two three".split()
  5. #ans: ['one', 'two', 'three']

Join

  1. # join list to string
  2. ",".join(["a", "b", "c"])
  3. #ans: "a,b,c"
  4. " ".join(["Hello", "World"])
  5. #ans: "Hello World"

Find and Index

  1. # find substring
  2. "hello world".find("world")
  3. #ans: 6
  4. "hello world".find("xyz")
  5. #ans: -1
  6. "hello world".index("world")
  7. #ans: 6

Replace

  1. # replace substring
  2. "hello world".replace("world", "Python")
  3. #ans: "hello Python"
  4. "aaa".replace("a", "b", 2)
  5. #ans: "bba" (replace first 2)

Startswith/Endswith

  1. # check start and end
  2. "hello".startswith("he")
  3. #ans: True
  4. "hello".endswith("lo")
  5. #ans: True

Count

  1. # count occurrences
  2. "hello".count("l")
  3. #ans: 2
  4. "banana".count("a")
  5. #ans: 3

Exercises - Part 1

  1. # case methods?
  2. "HeLLo".lower()
  3. #ans: "hello"
  4. "hello".upper()
  5. #ans: "HELLO"

Exercises - Part 2

  1. # strip only ends?
  2. " hello ".strip()
  3. #ans: "hello"

Exercises - Part 3

  1. # split with limit?
  2. "a-b-c-d".split("-", 2)
  3. #ans: ['a', 'b', 'c-d']

Exercises - Part 4

  1. # join with numbers?
  2. "-".join([1, 2, 3])
  3. #ans: TypeError (needs strings)
  4. "-".join(["1", "2", "3"])
  5. #ans: "1-2-3"

Exercises - Part 5

  1. # find vs index?
  2. "hello".find("x")
  3. #ans: -1
  4. "hello".index("x")
  5. #ans: ValueError

Exercises - Part 6

  1. # replace all?
  2. "aaa".replace("a", "b")
  3. #ans: "bbb"

Exercises - Part 7

  1. # case sensitive?
  2. "Hello".startswith("h")
  3. #ans: False
  4. "Hello".startswith("H")
  5. #ans: True

Exercises - Part 8

  1. # count overlapping?
  2. "aaa".count("aa")
  3. #ans: 1 (non-overlapping)

Exercises - Part 9

  1. # empty split?
  2. "".split()
  3. #ans: []
  4. " ".split()
  5. #ans: []

Exercises - Part 10

  1. # join empty list?
  2. ",".join([])
  3. #ans: ""

Google tag (gtag.js)