String Basics

Creating Strings

  1. # string creation
  2. text = "Hello"
  3. text2 = 'World'
  4. multiline = """This is
  5. a multiline
  6. string"""

String Indexing

  1. # access characters
  2. text = "Hello"
  3. text[0]
  4. #ans: 'H'
  5. text[-1]
  6. #ans: 'o'
  7. text[1]
  8. #ans: 'e'

String Slicing

  1. # slice strings
  2. text = "Hello, World!"
  3. text[0:5]
  4. #ans: 'Hello'
  5. text[7:]
  6. #ans: 'World!'
  7. text[:5]
  8. #ans: 'Hello'

String Concatenation

  1. # combine strings
  2. "Hello" + " " + "World"
  3. #ans: "Hello World"
  4. greeting = "Hello"
  5. name = "Alice"
  6. greeting + ", " + name
  7. #ans: "Hello, Alice"

String Repetition

  1. # repeat strings
  2. "Ha" * 3
  3. #ans: "HaHaHa"
  4. "=" * 10
  5. #ans: "=========="

String Length

  1. # get length
  2. len("Hello")
  3. #ans: 5
  4. len("")
  5. #ans: 0

Exercises - Part 1

  1. # negative index?
  2. s = "Python"
  3. s[-1]
  4. #ans: 'n'
  5. s[-2]
  6. #ans: 'o'

Exercises - Part 2

  1. # slicing with step?
  2. s = "abcdefg"
  3. s[::2]
  4. #ans: 'aceg'

Exercises - Part 3

  1. # reverse string?
  2. s = "Hello"
  3. s[::-1]
  4. #ans: 'olleH'

Exercises - Part 4

  1. # string immutability?
  2. s = "Hello"
  3. s[0] = 'h'
  4. #ans: TypeError (strings are immutable)

Exercises - Part 5

  1. # concatenation vs join?
  2. "a" + "b" + "c"
  3. #ans: "abc"
  4. "".join(["a", "b", "c"])
  5. #ans: "abc"

Exercises - Part 6

  1. # membership test?
  2. "ell" in "Hello"
  3. #ans: True
  4. "xyz" in "Hello"
  5. #ans: False

Exercises - Part 7

  1. # empty string?
  2. s = ""
  3. len(s)
  4. #ans: 0
  5. bool(s)
  6. #ans: False

Exercises - Part 8

  1. # string multiplication?
  2. "0" * 5
  3. #ans: "00000"

Exercises - Part 9

  1. # escape characters?
  2. s = "Line1\nLine2"
  3. len(s)
  4. #ans: 11 (\n is one character)

Exercises - Part 10

  1. # raw string?
  2. s = r"C:\new\path"
  3. #ans: "C:\\new\\path"

Google tag (gtag.js)