fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • slice

    We saw how to access individual characters of a string with []. It’s also possible to select a specific slice of a string - take several consecutive characters. This can be accomplished with the same [] brackets but by providing two numbers - the start and the end of the selection:
    s = 'This is a long long string'
    print(s[0: 1])      # T
    print(s[0: 2])      # Th
    print(s[0: 18])     # This is a long lon
    print(s[1: 3])      # hi
    print(s[1: -1])     # his is a long long strin
    print(s[3: -2])     # s is a long long stri
    print(s[-10: -2])   # ong stri
    Note 1: The start is always inclusive and the end is always exclusive ⇒ [start; end).
    Note 2: Both start and end can be negative - implying negative indexing.

    Challenge

    We should like to know what’s the central segment of a string.
    Given a string of length n, we would like to see the letters that span the positions from n/4 to 3n/4.
    The input contains a single line of text, which is guaranteed to have a length divisible by 4.
    The program should print the central segment.
    Input
    Output
    abcd
    bc
    abcdefgh
    cdef
     
    To check your solution you need to sign in
    Sign in to continue