String Slicing and Dicing
For the exercises below, first try using paper, pencil, discussion, and thinking (no computer) to solve them, before using the Python Interpreter to check your answers.
Assume these four string values and associated variables for the following exercises:
a = "computational thinking" b = "duke university" c = "python code"
Use the following String operators to form each of the words below.
- concatenation (as in
"a" + "bc", whose result is"abc") - multiplication by an int (as in
"abc" * 3, whose result is"abcabcabc") - indexing (as in
"abc"[0], whose result is"a") - slicing (as in
"abc"[0:2], whose result is"ab")
Examples
- "honk"
This is created from one slice, one catenation, one index.
c[3:6] + b[2]The value of
c[3:6]is hon because the slice starts at the character whose index is 3 which is "h" and goes up to, but does not include the character whose index is 6. The value ofb[2]is k because it is the single character whose index is 2. Concatenating these strings together makes"honk". - "puking"
This is created from two slices and one catenation.
a[3:5] + a[18:]The value of
a[3:5]is "pu". Note that the value ofa[18:]starts at the character at index 18 (the 19th spot) and goes until the end of the string, i.e., king.
Exercises
- "docking"
- "cocoa"
- "thought"
- "ratatatat"
- "duke is cool"
- "diversity nation"
- "money honey"