Difference between revisions of "CSC111 Lab 8 2014"

From dftwiki3
Jump to: navigation, search
(Splitting Strings)
(Splitting Strings)
Line 13: Line 13:
 
  >>> line = "The quick, red fox jumped.  It jumped over the lazy, sleepy, brown dog."
 
  >>> line = "The quick, red fox jumped.  It jumped over the lazy, sleepy, brown dog."
 
  >>> line
 
  >>> line
  'The quick, red fox jumped.  It jumped over the lazy, sleepy, brown dog.'
+
   
 
  >>> line.split()
 
  >>> line.split()
 
  >>> words = line.split()
 
  >>> words = line.split()
Line 23: Line 23:
 
   
 
   
 
  >>> words[-1]
 
  >>> words[-1]
 
+
 
  >>> words[-2]
 
  >>> words[-2]
 
   
 
   

Revision as of 14:02, 24 March 2014

--D. Thiebaut (talk) 14:01, 24 March 2014 (EDT)


This lab deals with strings and list operations, and transforming strings into lists and lists into strings.


Splitting Strings


Work in the console, and try these different commands. Observe what the different operations do.

>>> line = "The quick, red fox jumped.  It jumped over the lazy, sleepy, brown dog."
>>> line

>>> line.split()
>>> words = line.split()
>>> words

>>> words[0]

>>> words[1]

>>> words[-1]

>>> words[-2]

>>> chunks = line.split( ',' )      # split on commas
>>> chunks

>>> chunks = line.split( '.' )      # split on periods
>>> chunks

>>> words

>>> separator = "+"
>>> newLine = separator.join( words )    # join the words into a new string and use separator as the glue
>>> newLine

>>> separator = "$$$"
>>> newLine = separator.join( words )    # same but use $$$ as the glue
>>> newLine

>>> words       # verify that you still have individual words in this list

>>> newWords = [ words[0], words[3], words[4], words[7], words[8], words[12] ]   # create a new list of some words
>>> newWords

>>> " ".join( newWords )      # join strings in newWords list with a space