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

  • split()

    What if we would like to process words one by one? Python provides us with a utility function split() that splits the string into pieces and returns a list of those pieces:
    sentence = 'He ran out of money, so he had to stop playing poker.'
    words = sentence.split()
    print(words)   # ['He', 'ran', 'out', 'of', 'money,', 'so', 'he', 'had', 'to', 'stop', 'playing', 'poker.']
    split() can also accept a parameter based on which it will split the sentence:
    s = 'Item one, Item two, Item three'
    items = s.split(', ')
    print(items)   # ['Item one', 'Item two', 'Item three']
    In the last example, the items were divided by a comma and a space, so providing that to split hints it to split the sentence based on ', ' instead of any whitespace.
    Note: By default split() splits the string based on any whitespace (newline, space, tab, etc). If we provide it with some specific value say '\n', it will split only by a newline.

    Challenge

    Given a sentence, where the words are separated by a space, your task is to print the words one by one on separate lines.
    Input
    Output
    Python is awesome!
    Python is awesome!
     
    To check your solution you need to sign in
    Sign in to continue