0% found this document useful (0 votes)
52 views

String Slicing

This document discusses string slicing in Python. String slicing allows you to extract a substring from a string by specifying the start and end indices. Indices start at 0, and the end index is not included. You can slice from the start or end of the string by leaving out the start or end index. Negative indices count backwards from the end of the string. An example shows how to use slicing to extract the domain name from an email address.

Uploaded by

Varun H R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

String Slicing

This document discusses string slicing in Python. String slicing allows you to extract a substring from a string by specifying the start and end indices. Indices start at 0, and the end index is not included. You can slice from the start or end of the string by leaving out the start or end index. Negative indices count backwards from the end of the string. An example shows how to use slicing to extract the domain name from an email address.

Uploaded by

Varun H R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

STRING SLICING

 You can return a range of characters by using the slice syntax.

 Specify the start index and the end index, separated by a colon, to return a
part of the string.

Example:

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5])

Output:

llo

Note: The first character has index 0.

Slice From the Start

 By leaving out the start index, the range will start at the first character:

Example:

Get the characters from the start to position 5 (not included)

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]'

print("The original string is : " + str(test_str))

res = test_str[test_str.index('@') + 1 : ]

print("The extracted domain name : " + str(res))

Output:

The original string is : [email protected]

The extracted domain name : vviet.com

You might also like