SLICING
In Python, slicing is a string operation used to extract a portion (substring) of a sequence such as a string, list, or tuple. Slicing uses the syntax [start:end], where start is the index of the first element to include and end is the index of the first element to exclude. Python also allows optional step values with [start:end:step], which specify the interval between elements. Negative indexes can be used to count from the end of the sequence, making it convenient to access elements relative to the sequence’s tail. Slicing always returns a new sequence and does not modify the original. This concept is similar to the substring operation in C or C++, though Python provides additional flexibility like negative indexing and step values.
EXTRACTING STRINGS
text = "soundtrack";
print(text[0:5]);
* OUTPUT
soundMODIFYING STRINGS
Python strings are immutable. This code does not modify the original string in place. Instead, it constructs a completely new string. It takes the first two characters of the original string ("Ch"), inserts the letter "e", and then appends the remaining characters ("f"). The final result is "Chef", stored in new_string, while the original value "Chaf" remains unchanged.
string = 'Chaf'
new_string = string[:2] + 'e' + string[3:]
print(new_string) # Output: Chef
# This code modifies the string 'Chaf' to 'Chef'
* ChefREVERSING THROUGH SLICING
In Python, slicing normally traverses a string from left to right as it processes characters in increasing index order. However, when a negative step value is used, the slice direction is reversed, causing Python to move through the string from right to left instead. This reverse traversal effectively flips the order of the characters, allowing you to reverse an entire string—or a selected portion of it—simply by specifying a negative step.
Last updated