Lab Worksheet 8 Solutions

Problem 1: Using only list indexing and the string function split(), write code that extracts the weight (here the number 7) from the string data defined below, and print out the result. What is the type of your final result? Use python to find out.

In [1]:
data_string = "height: 15; weight: 7; width: 5;"

# here are two approaches for solving this question (although there are more ways!):

## One ##
data2 = data_string.split(": ")
weight = data2[2][0]
print(weight, type(weight))

## Two ##
data2 = data_string.split("; ")
weight_raw = data2[1]
weight = weight_raw.split(" ")[1]
print(weight, type(weight))
7 <class 'str'>
7 <class 'str'>

Problem 2: Using only string indexing, write code that does each of the following. In each case, store the result in a new variable and print its contents.

  • Extract the first 10 characters from the string data_string.
  • Extract characters 27 to 52 (corresponding to the upper-case letters of the alphabet) from the string data_string.
  • Extract characters 1 to 26 (corresponding to the lower-case letters of the alphabet) and characters 53 to 62 (corresponding to the numbers) from the string data_string and combine them into a single, new string that should look like this: "abcdefghijklmnopqrstuvwxyz0123456789"
  • Replace the letter at position 5 in data_string (the lower-case e) with a captial X. Do not use the function replace().
  • Take the resulting string from the previous point and convert it all to upper case.
In [2]:
data_string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

# Extract the first 10 characters
print(data_string[:10])

# Extract characters 27-52
print(data_string[26:52])

# Extract characters 1-26 and 53-62
new = data_string[:26] + data_string[52:]
print(new)

# Replace e with X
new2 = data_string[:4] + "X" + data_string[5:]
print(new2)

# Turn the previous string to uppercase
print(new2.upper())
abcdefghij
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789
abcdXfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
ABCDXFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789