Explain string slicing?

String slicing in Python allows you to extract a portion of a string by specifying a range of indices. The syntax for slicing is:

string[start:end:step]
  • start: The index where the slice begins (inclusive).
  • end: The index where the slice ends (exclusive).
  • step: The interval between each index in the slice (optional).

Key Points:

  • Indices start at 0.
  • You can use negative indices to count from the end of the string.
  • If start is omitted, it defaults to the beginning of the string.
  • If end is omitted, it defaults to the end of the string.
  • If step is omitted, it defaults to 1.

Examples:

text = "Hello, World!"

# Get the first 5 characters
print(text[:5])  # Output: 'Hello'

# Get characters from index 7 to 11
print(text[7:12])  # Output: 'World'

# Get the last 6 characters
print(text[-6:])  # Output: 'World!'

# Get every second character
print(text[::2])  # Output: 'Hlo ol!'

String slicing is a powerful feature that allows for flexible manipulation of strings. Let me know if you need more examples or explanations!

0 Comments

no data
Be the first to share your comment!