12. String Operations

12.1. Concatenation

1a = "Potato"
2b = "when born"
3print(a + b)
4print(a * 3)
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.1.1 (cl_l05_12a_en)

12.2. Slicing

  • We can perform the slicing operation using [start_index:end_index]

1x = "0123456789"
2print(x[0:2])
3print(x[1:2])
4print(x[2:4])
5print(x[0:5])
6print(x[1:8])
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.2.1 (cl_l05_12b_en)

  • We can omit indices, replacing the corresponding index, and we can also have negative indices: -1 last, -2 penultimate

1x = "0123456789"
2print(x[:2])
3print(x[4:])
4print(x[4:-1])
5print(x[-4:-1])
6print(x[:])
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.2.2 (cl_l05_12c_en)

12.3. Formatting

  • Joining multiple strings is not always practical

  • We can use placeholders to replace values within strings

1age = 20
2print("Juan is %d years old" % age)
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.3.1 (cl_l05_12d_en)

  • The main placeholders are %d for integers, %s for strings, and %f for floating-point numbers

  • % 03d complete with additional zeros

  • % 3d means three positions without additional zeros

1age = 20
2print("[%03d]" % age)
3print("[%3d]" % age)
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.3.2 (cl_l05_12e_en)

  • %5.2f means 5 characters in total and 2 decimals

1print("$%5.2f pesos" % 23)
line that just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Activity: CodeLens 12.3.3 (cl_l05_12f_en)

12.4. f-strings

  • Another way to join strings is through f-strings

  • Everything inside braces {} will be replaced if previously defined. In the example, .2f means two decimal places.

Activity: 12.4.1 ActiveCode (ac_l05_12_en)

You have attempted 1 of 3 activities on this page