CS105
LAB 7- Python 3


Strings

1. Consider the following string:

>>> x = "I am you are"

>>> x[0]

>>> x[-1]

>>> x[2:4] + x[6:8]

>>> x[:4]

>>> x[5:]

Given x, provide a way to access x[5:8] (="you") with negative indices (Hint: use len( ))

 

2. Practice Creating String Expressions
Assume that the following statements have already been executed:

    import string
    str1 = "Go"
    str2 = "Terriers!"
For each of the following values, construct a Python expression involving string operations on str1 and/or str2 that evaluates to that value.

Your answers to parts i and iv may include a single string literal (e.g., 'e'), and your answer to part v may include two string literals. No other string literals should be used.

  1.     'Go Terriers!'
  2.     'GOT!'
  3.     'Go!Go!Go!' (Note: str1 and str2 should each appear only once in your answer.)
  4.     ['Te', '', 'ie', 's!']
  5.     'Torriors!'

 

3. Consider the following expression:

>>> "base" in "datacase"

What is the type of this expression?

 

4. Assume that the following raw_input statements are both executed:

>>> mine=raw_input("My favorite number: ")

>>> yours=raw_input("Your favorite number: ")

Write one or more statements that prints the sum of our (mine and yours) favorite numbers! (Hint: Don't forget that raw_input always gives you a string. How can you change the string to an integer?)

 

5. Write a line of code that assigns 100 hyphens ("-") followed by 100 question marks ("?") to a variable named "manyDashesAndQuestionmarks".

 

6. Write a program to read a word into the variable word and print each letter of the word twice on its own line.

Example: if the user inputs "CS", the output should be:

C C
S S

 

7. A bunch of people voted their favorite Queen song. The results were gathered in this Python list of the form [votes1, song1, votes2, song2, votes3,...]

Write a program that assigns the list as shown below to myList and performs a for loop. In the end it outputs two things. The sum of the votes and the songs!

Example (and test case):

>>> myList = [35, "bicycle race", 40, "bohemian rhapsody", 50, " under pressure"]

press F5 to run songsAndVotes.py. Your output should as follows:

Votes: 125

Songs: bicycle race, bohemian rhapsody, under pressure


8. Useful functions from the string library:

>>> import string

>>> temp= "There's four new colors in the rainbow, an old man's taking polaroids"

>>> parts1=string.split(temp)

>>> parts2=string.split(temp,",")

>>> temp1=string.join(parts1)

>>> temp2=string.join(parts2)

Is temp1==temp?

What about temp2==temp?

What does the following command do?
>>> string.replace(temp, " ", ";")


CS105