Introduction
The term slicing in programming usually refers to obtaining a substring, sub-tuple, or sublist from a string, tuple, or list respectively.
Python offers an array of straightforward ways to slice not only these three but any iterable. An iterable is, as the name suggests, any object that can be iterated over.
In this article, we'll go over everything you need to know about Slicing Strings in Python.
Slicing a String in Python
There are a couple of ways to slice a string, most common of which is by using the :
operator with the following syntax:
string[start:end]
string[start:end:step]
The start
parameter represents the starting index, end
is the ending index, and step
is the number of items that are "stepped" over.
Let's go ahead and slice a string:
string = 'No. I am your father.'
print(string[4:20])
This will omit the first four characters in the string:
I am your father
Finding the Prefix and Suffix of Length n with Slice Notation
To find the prefix or suffix of length n
of a string, we'll use the same approach that can be used to find a tail or head of a list. We'll slice from the start to n
and from -n
to the end of the string.
In this case, -n
will start counting from the end of the string, backwards, giving us a suffix:
n = 4
string = 'Now, young Skywalker, you will die.'
# Prefix of length n
print(string[:n])
# Sufix of length n
print(string[-n:])
This results in:
Now,
die.
Reverse a String using Slice Notation
To reverse a string, we can set the step
of the slice notation to -1
. This makes the step go backwards, including each element it steps on, resulting in the string being printed back in reverse:
string = 'I’ll never turn to the dark side. You’ve failed, your highness. I am a Jedi, like my father before me.'
print(string[::-1])
This code would result in:
.em erofeb rehtaf ym ekil ,ideJ a ma I .ssenhgih ruoy ,deliaf ev’uoY .edis krad eht ot nrut reven ll’I
Finding Every n-th Character in a String
Extracting every n-th character comes down to setting the step parameter to n
. If you want every second character, you'd step over every second chracter as well:
n = 3
string = 'There’s always a bigger fish.'
print(string[::n])
This code will print out every third letter:
Trslyaiefh
Conclusion
Slicing any sequence in Python is easy, simple, and intuitive. Negative indexing offers an easy way to acquire the first or last few elements of a sequence, or reverse its order.
In this article, we've covered how to apply the Slice Notation on Strings in Python.
from Planet Python
via read more
No comments:
Post a Comment