Strings Exercises

String Basics

  1. Write Python code to do the following:
    1. Assign your first name to a variable named fullName
    2. Append (or add) a space and your last name to fullName
    3. Print out each of the characters in fullName with a while loop
    4. Display the number of characters in fullName
  2. Answer the following questions then confirm with your neighbor:
    1. What is the index of the first letter of your first name in fullName?
    2. What is the index of the first letter of your last name in fullName?
    3. How can we determine the length of any str variable in python?
    4. What will be the result of the following python code?
      fullName[0] = 'Z'
    5. What does the following python script print out (if anything)?
      word = "stressed"
      
      startIndex = -1
      lastIndex = 0 - len(word)  # index of first letter
      step = -1
      for charIndex in range( startIndex, lastIndex + step, step):
          # print the character in word specified by charIndex (and don't add a
          # newline at the end)
          print( word[ charIndex ], end='')
      
      # display just a newline
      print()

String Methods

For each of the following methods, write down what they do including what they return:
  1. String testing methods:
  2. String modification methods:
  3. String searching and replacing methods:
  4. Non-string methods:

String Slicing

  1. What will be the result of each of the following statements?
    1. print( fullName )
    2. print( fullName[  5:8  ])
    3. print( fullName[   :8  ])
    4. print( fullName[  5:   ])
    5. print( fullName[   :   ])
    6. print( fullName[ -3:   ])
    7. print( fullName[-50:   ])
    8. print( fullName[   :-2 ])
    9. print( fullName[  5:50 ])
    10. print( fullName[  5:10:2])
    11. print( fullName[  5:10:3])
  2. What does the following python code display?
    # Indices:
    #                  111
    #        0123456789012  
    river = "Chattahoochee"
    
    print( river )
    print( river[1:4] )
    print( river[2:4] )
    print( river[4:5] + river[6:7] + river[11:12] )
    print( river[6:8] + ', ' + river[6:8] + ', ' + river[10:] )
    print( river[:4] )
    print( river[-3:] )
    print( river[:-3] )
    print( river[9:1] )
    

Formatted String Literals

Strings can be formatted as in the following example:
mainDish = "pizza"
scoopsOfIceCream = 3
message = f'Dinner tonight is {mainDish} and {scoopsOfIceCream} types of ice-cream!'
print(message)
Output:
Dinner tonight is pizza and 3 types of ice-cream!
  1. The following Python code:
    piApprox = 22/7
    print( '22/7 is', piApprox )
    displays
    22/7 is 3.142857142857143
    Use the piApprox variable and a formatted string (f-string) to display the following (exactly as shown):
    PI is approximately 3.14286
  2. Given the following python code,
    iceCreamScoopCost = 1.50
    display the following (exactly as shown) using an f-string and the variable iceCreamScoopCost:
    The cost of one scoop is $1.50 and the cost of two scoops is $3.00.
  3. Use f-strings to display the following (exactly as shown):
                      Early computers limited the width of one line to 80 characters
                                    These lines are right-justified at 80 characters
    
                    This line is centered in an 80-character column

String Comparison and Operators:

  1. What does the following Python code display and why?
    print( chr( 67 ) )
    print( chr( 68 ) )
    print( chr( 69 ) )
    
    print( ord( 'C' ) )
    print( ord( 'S' ) )
    
    Hint: What is the ASCII value for 'C'?
  2. Fill in the table with True or False:
    OP
    < > == != in not in
    A 'python' OP 'pytHon'
    'python' < 'pytHon'
    False
    C 'py' OP 'python'
    D 'python' OP 'rocks'
    E 'python' OP 'python'

String split() and join()

str.split()

str.split( substring ) cuts str everywhere it finds substring. It returns each part as a str in a list. By default, split uses ' ' (a single space) as the delimiter.
For example, given string = 'I love Python!', then
string.split() returns: ['I', 'love', 'Python!']
and
string.split('o') returns: ['I l', 've Pyth', 'n!']
  1. For each of the strings below, calculate how many cuts (i.e., how many elements are in the resulting list) when 1) split() is called on the string and 2) split( 'o' ) is called:
    1. I love python!
    2. Hello, world!
    3. supercalifragilisticexpialidocious
    4. See spot run. See spot run fast.
  2. What does the following code return:
    1. dataHeaderLine = 'first name\tlast name\tage\tphone number\taddress'
      dataHeaderLine.split( )
    2. dataHeaderLine = 'first name\tlast name\tage\tphone number\taddress'
      dataHeaderLine.split('\t')
    3. eventDescription = "We're going to meet @ the building @ 7:00 PM"
      eventDescription.split('@')

str.join()

str.join( listArg ) takes all of the elements in listArg and puts the contents of str between them. For example, given:
dataHeaderList = ['first name', 'last name', 'age', 'phone number', 'address']
separator = '\t'
then,
separator.join( dataHeaderList )
returns
first name	last name	age	phone number	address