Python Tutorial
Python String Slicing Explained with Examples
What is String Slicing in Python?
A range of characters can be returned using the slice syntax. Specify the start and end indexes, separated by a colon, to retrieve a part of the text.
Example:
b = "Hello WSC"
print(b[2:5])
Output
llo
Slice From the Start
The range will begin with the first character if the start index is omitted:
Example:
b = "Hello WSC"
print(b[:5])
Output
Hello
Slice To the End
The range will go to the end if the end index is omitted.
Example:
Get the characters from position 2, and all the way to the end:
b = "Hello WSC"
print(b[2:])
Output
llo, World!
Negative Indexing
To begin the slice from the end of the string, use negative indexes:
Example
b = "Hello, World"
print(b[-5:-1])
Output
orld
Example
b = "Hello, World"
print(b[0:5:2])
Output
Hlo
Check String
The keyword can be used to see if a phrase or character is contained in a string.
Code:
text = "Welcome to wscube tech"
print("tech” in text)
Output:
True
Iterate Strings in Python
It is possible to cycle over a string using a For loop. This is an example of how to count the number of 'l's in a string.
Example:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Output
3 letters found