String slicing in Python lets you extract a part (substring) from a string using the syntax string[start:end] or string[start:end:step]. The start index is included, but the end index is excluded. You can also use negative indexes to count from the end of the string and a step value to skip characters or even reverse the string.
0.1).-1).The general slicing syntax in Python is:
string[start:end]
string[start:end:step]
# start → index to begin from (included)
# end → index to stop at (excluded)
# step → jump size (default = 1)
If start is omitted, Python starts from the beginning of the string. If end is omitted, Python slices until the end. If step is negative, the slice goes in reverse.
Extract different parts of a string using start and end indexes.
text = "PythonProgramming"
print(text[0:6]) # Python
print(text[6:]) # Programming
print(text[:6]) # Python
Use the step value to skip characters while slicing.
text = "PythonProgramming"
print(text[0:16:2]) # Pto rgamn
print(text[::3]) # Phgai
Negative indexes let you slice from the end of the string.
text = "PythonProgramming"
print(text[-1]) # g
print(text[-7:-1]) # ramming
print(text[:-7]) # PythonProg
Use a negative step to reverse the entire string.
text = "Python"
print(text[::-1]) # nohtyP
Combine all three parameters to get specific patterns from a string.
text = "PythonProgramming"
print(text[1:12:2]) # yhnPorm
text[0:6] → characters from index 0 to 5 → "Python".text[6:] → from index 6 to the end → "Programming".text[:6] → from start until index 6 (excluded) → "Python".text[0:16:2] → every 2nd character from index 0 to 15.text[::3] → every 3rd character from the entire string.text[-7:-1] → 7th character from the end up to (but not including) the last character.text[::-1] → full string reversed.text[1:12:2] → from index 1 to 11, taking every 2nd character.Notice how the end index is never included in the slice, and how a negative step reverses the direction of slicing.
1.Result will appear here after you click Run Slice.
[::] to create a full copy of a string."PythonProgramming" using slicing."DataScience" using slicing."MachineLearning" using a step value.start, end, and step values.