Slicing Strings
Slicing is a technique used to extract a portion of a string in Python. It allows you to specify a range of indices to extract a substring.
Basic Slicing
To slice a string, you can use square brackets []
and specify the start and end indices of the substring you want to extract. For example:
text = 'Hello, World!'
print(text[7:12]) # Output: 'World'
Note that the end index is exclusive, so the character at the end index is not included in the substring.
Omitting Start or End Index
If you omit the start index, Python will start from the beginning of the string. If you omit the end index, Python will slice until the end of the string. For example:
print(text[:5]) # Output: 'Hello'
print(text[7:]) # Output: 'World!'
Negative Indexing
You can also use negative indexing to slice a string. Negative indices count from the end of the string. For example:
print(text[-6:-1]) # Output: 'World'
Conclusion
Slicing strings in Python is a powerful technique for extracting substrings from a string. By using index notation and understanding how slicing works, you can manipulate strings to extract the information you need in your programs.