Manipulating strings is a powerful skill to learn. So far, we have focused on the format method. This involved formatting numbers and substituting values into a string. In a way, the format method is used for combining strings. String slicing is a useful way to take apart strings. The syntax for slicing a string is "myString"[start:end] where start is the index of the string you want to start slicing from and end is the index you want to stop at. The starting index is inclusive and the ending index is exclusive. Also, don't forget indexes start counting at zero! You can specify either or both indexes in the slice operation.
test_string = 'Happy Birthday' print(test_string)
The above examples show the basics string slice. Note how the ending index of the slice is exclusive. A very important note to make is that this slice operation is not destructive. It does NOT modify the string you are slicing in any way. It actually returns a completely new string as the result of the operation:
Happy Happy Birthday
The above examples use both the starting and ending index in the slice. However, you don't have to specify one or the other, or both! If neither index is given, the whole string is copied as a result:
You can also specify one or the other. If no starting index is given, it will default to index 0.
If no ending index is given, it will default to the number of characters in the string.
Remember that the ending index is exclusive!
The slice operation is very powerful. We aren't limited to using only positive numbers for the start and end index. This is completely against many rules when accessing an index in arrays or lists in many programming languages. If a negative number is used for the end index, it is essentially saying "exclude the last n characters from the end."
You can also use a negative number for the start index. In this case, it gives the characters starting n characters from the end of the string.
Using negative indices in the slice operation is an easy way to manipulate a string without knowing how many characters it contains. Though, you can find the length of a string by using the built-in len function. len will return the length of an object, this includes strings, dictionaries, and lists among other things.