Slicing

Slicing in Python is a feature that enables accessing parts of the sequence. In slicing a string, we create a substring, which is essentially a string that exists within another string. We use slicing when we require a part of the string and not the complete string. Syntax :

string[start : end : step]

  • start : We provide the starting index.
  • end : We provide the end index(this is not included in substring).
  • step : It is an optional argument that determines the increment between each index for slicing.

Example 1 : 

python3




# declaring the string
str ="Geeks for Geeks !"
 
# slicing using indexing sequence
print(str[: 3])
print(str[1 : 5 : 2])
print(str[-1 : -12 : -2])


Output

Gee
ek
!seGrf

Example 2 : 

python3




# declaring the string
str ="Geeks for Geeks !"
 
print("Original String :-")
print(str)
 
# reversing the string using slicing
print("Reverse String :-")
print(str[: : -1])


Output

Original String :-
Geeks for Geeks !
Reverse String :-
! skeeG rof skeeG


How To Index and Slice Strings in Python?

The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. As the string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing.

Similar Reads

Indexing

Indexing means referring to an element of an iterable by its position within the iterable. Each of a string’s characters corresponds to an index number and each character can be accessed using its index number. We can access characters in a String in Two ways :...

Slicing

...

Contact Us