String slicing in Python is a technique used to extract a portion (substring) of a string by specifying a range of indices. It allows you to create a new string from an existing string by defining a start index and an end index.
Syntax:
substring = original_string[start:end]
- start: The index where the slice begins (inclusive).
- end: The index where the slice ends (exclusive).
Example:
text = "Hello, World!"
substring = text[0:5] # Extracts characters from index 0 to 4
print(substring) # Output: Hello
Additional Features:
- If you omit the start index, it defaults to 0.
- If you omit the end index, it defaults to the length of the string.
- You can also specify a step value to skip characters.
Example with Step:
text = "Hello, World!"
substring = text[::2] # Extracts every second character
print(substring) # Output: Hlo ol!
String slicing is a powerful feature that allows for flexible manipulation of strings. If you have more questions or need further examples, feel free to ask!
