0
0
Pythonprogramming~5 mins

String slicing behavior in Python

Choose your learning style9 modes available
Introduction
String slicing helps you get parts of a word or sentence easily, like cutting a piece from a cake.
You want to get the first few letters of a name.
You need to remove the last character from a word.
You want to reverse a string to check if it reads the same backwards.
You want to get every second letter from a sentence.
Syntax
Python
string[start:stop:step]
start is where slicing begins (included). If empty, starts from the beginning.
stop is where slicing ends (excluded). If empty, goes to the end.
step is how many characters to jump each time. Default is 1.
Examples
Gets letters from position 1 up to 3 (4 is excluded), so prints 'ell'.
Python
text = "hello"
print(text[1:4])
Gets letters from start up to position 2, prints 'wor'.
Python
text = "world"
print(text[:3])
Gets letters from position 2 to the end, prints 'thon'.
Python
text = "python"
print(text[2:])
Gets every second letter from start to end, prints 'ace'.
Python
text = "abcdef"
print(text[::2])
Sample Program
This program shows different ways to slice a string: from the start, middle, end, and reversed.
Python
word = "programming"

# Get first 4 letters
first_part = word[:4]

# Get letters from position 3 to 7
middle_part = word[3:8]

# Get last 3 letters
last_part = word[-3:]

# Reverse the word
reversed_word = word[::-1]

print(f"First 4 letters: {first_part}")
print(f"Letters 3 to 7: {middle_part}")
print(f"Last 3 letters: {last_part}")
print(f"Reversed word: {reversed_word}")
OutputSuccess
Important Notes
If start or stop is negative, counting starts from the end of the string.
If step is negative, slicing goes backwards.
Slicing never changes the original string; it creates a new one.
Summary
String slicing extracts parts of a string using start, stop, and step positions.
Start is included, stop is excluded in the slice.
You can use negative numbers to count from the end or reverse the string.