Difference between revisions of "CSC111 Lab 8 2014"

From dftwiki3
Jump to: navigation, search
(Splitting Strings)
(Splitting Strings)
Line 44: Line 44:
 
  >>> words      <font color="magenta"># verify that you still have individual words in this list</font>
 
  >>> words      <font color="magenta"># verify that you still have individual words in this list</font>
 
   
 
   
  >>> newWords = [ words[0], words[3], words[4], words[7], words[8], words[12] ]   <font color="magenta"># create a new list of some words</font>
+
  >>> newWords = [ words[0], words[3], words[4], words[7], words[8], words[12] ] <font color="magenta"># create a new list </font>
 
  >>> newWords
 
  >>> newWords
 
   
 
   
 
  >>> " ".join( newWords )      <font color="magenta"># join strings in newWords list with a space</font>
 
  >>> " ".join( newWords )      <font color="magenta"># join strings in newWords list with a space</font>

Revision as of 14:03, 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 
>>> newWords

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