12. String Operations¶
The basic operations are slicing, concatenation, and formatting.
Slicing allows you to use part of a string
Concatenation, in contrast, is used to join two or more strings
Finally, formatting is used heavily when sending messages to the console and consists of using strings as templates where we can insert data
12.1. Concatenation¶
12.2. Slicing¶
We can perform the slicing operation using
[start_index:end_index]
We can omit indices, replacing the corresponding index, and we can also have negative indices: -1 last, -2 penultimate
12.3. Formatting¶
Joining multiple strings is not always practical
We can use placeholders to replace values within strings
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
%5.2f
means 5 characters in total and 2 decimals
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.