0 Comments

Strings in Python are sequences of characters, and slicing is a powerful technique to extract specific portions. By specifying start and end indices within the string, you can easily manipulate text data.

Basic Slicing

To slice a string, use square brackets [] with the start and end indices separated by a colon :. Indexing begins at 0.

Example:

my_string = "Hello, world!"
print(my_string[0:5])  # Output: Hello
print(my_string[7:])   # Output: world!

Omitting Indices

Omitting the Start Index: If you leave out the start index, slicing begins at the beginning of the string.

Omitting the End Index: If you leave out the end index, slicing continues to the end of the string.

Example:

my_string = "Python is awesome!"
print(my_string[:6])   # Output: Python
print(my_string[7:])   # Output: is awesome!

Using Negative Indices

Negative indices allow you to count from the end of the string, providing flexible slicing options.

Example:

my_string = "Hello, world!"
print(my_string[-6:])  # Output: world!

Step Slicing

For skipping characters, add a step value after the second colon ::. This lets you slice with intervals.

Example:

my_string = "Python is awesome!"
print(my_string[::2])  # Output: Pto i aewsm!

Reversing Strings

To reverse a string, use a negative step value of -1.

Example:

my_string = "Hello, world!"
print(my_string[::-1])  # Output: !dlrow ,olleH

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts