How to Slice Strings in Python?

Estimated read time 2 min read

To slice strings in Python, you can use square brackets [] with the index or indices of the characters you want to extract. Here are a few examples of how to slice strings in Python:

Example 1: Slicing a string from the beginning to a specified index

s = "Hello, world!"
print(s[:5]) # prints "Hello"

In this example, we define a string s with the value “Hello, world!”. We then use the slice notation [:5] to extract the characters from the beginning of the string up to (but not including) the 5th index. The resulting string is “Hello”.

Example 2: Slicing a string from a specified index to the end

s = "Hello, world!"
print(s[7:]) # prints "world!"

In this example, we use the slice notation [7:] to extract the characters from the 7th index to the end of the string. The resulting string is “world!”.

Example 3: Slicing a string between two specified indices

s = "Hello, world!"
print(s[7:12]) # prints "world"

In this example, we use the slice notation [7:12] to extract the characters from the 7th index up to (but not including) the 12th index. The resulting string is “world”.

You can modify these examples to slice strings in different ways, such as by using negative indices or by specifying a step value.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply