12. String Operations

12.1. Concatenation

Activity: CodeLens 12.1.1 (cl_l05_12a_en)

12.2. Slicing

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

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

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

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

Activity: CodeLens 12.3.2 (cl_l05_12e_en)

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

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.

System Message: ERROR/3 (/home/runner/work/PyZombis/PyZombis/_sources/lectures/TWP05/TWP05_12_en.rst, line 81)

Duplicate ID – see lectures/TWP05/TWP05_12, line 85

.. activecode:: ac_l05_12
   :nocodelens:
   :stdin:

   price = 10.123
   print(f"The price is: ${price:.2f}")
You have attempted of activities on this page