CSC111 Lab 4 2015b

From dftwiki3
Revision as of 15:21, 27 September 2015 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- ===String Slices=== * Use Python in interactive mode and try the following Python statements. Try to figure out the answers to the questions. <code><pre> Pyth...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 15:21, 27 September 2015 (EDT)



String Slices

  • Use Python in interactive mode and try the following Python statements. Try to figure out the answers to the questions.
Python 2.6 (r26:66714, Nov  3 2009, 17:33:38) 
[GCC 4.4.1 20090725 (Red Hat 4.4.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "H:/English103/paper1.doc"
>>> a

>>> len( a )

>>> a[0 : 2]

>>> a[3 : 13]

>>> a[-3 : -1]

>>> a[-5 : -1]

>>> a[-5 : ]                  (no, I didn't forget the second number!)

>>> a[ : 3]                   (and no again, I didn't forget the first number!)

>>> a[3 : -3]

>>> b = "C:/My Documents/paper2.htm"

You will have discovered that both a and b contain strings representing the name of files on a computer.

Question 4
What slice that will return the drive information for a (i.e. 'H:')? If you replace a by b, does your statement still return the drive for b? If not, figure out a way to take the slice that works independently of the string a, or b.
Question 5
What is the slice that will return the extension of a (i.e. doc)? If you replace a by b in your statement, do you get the extension of b? If not, figure out a way to write the slice that will work independently of the length of the file name.
Question 6
Once you have figured out the answers to Question 2, write a simple Python program that asks the user for a file name, such as the ones we used for a or b above, and that replaces the extension with the string "txt". Your program should display the final string, as illustrated below. Make sure you put your program in a main() function (a good reflex to start having!)
Example
Filename? C:/My Documents/paper02182010.doc
C:/My Documents/paper02182010.txt