Slicing in Python refers to extracting specific portions (substring) of a string using indices. Slicing strings Python involves obtaining a sub-string from a given string by slicing it from start to end. Using index positions, slicing allows you to capture substrings or characters, creating more flexible manipulation and analysis of text data. Moreover, one can return an array of characters with the slice syntax.
This blog will thoroughly explain string slicing in python, syntax, examples, and how indexing can be done in Python.
A slice syntax helps you to return a range of characters. You have to define the start and the end index. Separate them by a colon, to return a part of the string.
Example:
Get the characters from 2nd position to 6th position (which is not included):
b = "Welcome, Home"
print(b[2:6])
Output : lcom
For slicing, you can use different methods among which two are very common. One is by using the in-build slice() another is by using the [:] array slice.
Using a slice() method
In this method, the slice() constructor creates a slice object. Thus, this object represents the set of indices. A range like start, stop, and step is there to specify it. Below is the syntax to explain string slicing in Python via this method.
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
Return Type: Delivers a sliced object with only the elements in the given range.
Using the array slicing [:: ] method
In slicing strings Python learning, you can also use indexing syntax as an alternative for the slice object. Moreover, this is an easy way of slicing a string via list slicing and Array slicing. It is convenient both syntax-wise and execution-wise. The process of a start, end, and step is the same as that of the slice() constructor.
Syntax:
Let's understand basic string slicing operations with examples.
S = 'DICTIONARY'
print(S[2:7]) # CTION
Slicing with Negative Indices
When slicing a string, you can also specify negative indices.
S = 'DICTIONARY'
print(S[-7:-2]) # ANOIT
Slicing strings in Python with Positive & Negative Indices
It is possible to define both positive and negative indices simultaneously.
S = 'ABCDELGHK'
print(S[2:-5]) # CD
Specify Step for the slice- Using the step parameter, you can define the slicing step. The optional step parameter has a default value of 1.
# Return every second item between positions 2 to 7
S = 'AMCDEKGHK'
print(S[2:7:2]) # CEG
Reversing a String- You can reverse a string by leaving off the start and stop indices and entering a step of -1.
S = 'MONDAY'
print(S[::-1]) # YADNOM
So far we have seen slicing strings in Python. But, Indexing is different from it. Indexing is referring to an item of an iterable by its place within the iterable. Each character in a string has an index number that you can use to retrieve that character in the string.
Accessing characters in a String can be done in these two ways:
Indexing starts from 0 in Python. Thus, the first element in a sequence is at position 0. The second element appears at position 1, and so forth.
To reach an element in a sequence, use square brackets [] with the index of the element you need to access.
Consider the below example:
my_list = ['monday', 'tuesday', 'wednesday', 'date']
print(my_list[0]) # output: 'Monday'
print(my_list[1]) # output: 'tuesday'
Omitting the starting index will slice all characters from the string's start to a specific point in the middle. Now, provide the end index. The range starts at the first character and goes all the way to the last character before the end index.
The syntax for this notation:
string[:end_position].
Slicing a string's first five characters:
string[:5]
This results in a substring that runs from index 0 to index 4.
testString2 = "Welcome! Home"
print(testString2[:5])
Welco
By passing the starting index, all characters from the beginning of the string to a specific point in the centre will be cut. Now, provide the end index as usual. The range begins at character zero. But, it extends all the way to character zero before the end index.
The syntax for python slice string by character:
string[start_position:]
testString2 = "Welcome! Home"
print(testString2[5:])
e! Home
Slicing strings is also possible with negative indexing. This also helps extract the second and third final characters from a string. But there is no need to carry out a lot of logical procedures. The same principles of positive and negative indexing apply to cutting. It denotes the beginning of the substring and is inclusive. But, the first character that is excluded from the new substring by the ending position, which is exclusive, is marked.
testString2 = "Welcome! Heaven"
print(testString2[-3:-1])
ve
Python supports slicing strings to create substrings. Because Python strings are immutable, cutting a string into smaller pieces results in the original string remaining the same. You can better understand slicing strings in Python by practising the various syntax we have discussed. For more knowledge on Python index and strings, join the Python certification course by The IoT Academy!
Ans. [2: ] is a slice notation. You can perform it on a str. Hence, you can retrieve all of the characters of the string beginning from index 2.
Ans.A separator defines how to split a string. It can be by a comma, character etc. Whereas, a Limit Limits the number of splits for a given number.
Ans.The main difference between the two is that of the parameters. The two parameters of substr() are start and length. But for substring(), they start and end.
About The Author:
Digital Marketing Course
₹ 9,999/-Included 18% GST
Buy Course₹ 29,999/-Included 18% GST
Buy Course