String Slicing
String Slicing
Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example:
b = "Hello, World!"
print(b[2:5])
Output:
llo
By leaving out the start index, the range will start at the first character:
Example:
b = "Hello, World!"
print(b[:5])
Output:
Hello
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Output:
llo, World!
Negative indexing
Use negative indexes to start the slice from the end of the string:.
Example
Get the characters From "o" in "World!" (position -5) to, but not included "d"
in "World!" (position -2)
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
1
Example:
Write a python program to extract domain name from email address using
index and slicing.
test_str = '[email protected]'
res = test_str[test_str.index('@') + 1 : ]
Output: