Skip to content

Instantly share code, notes, and snippets.

@PramodDutta
Created February 6, 2024 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PramodDutta/0026d80c26ce4141e06e0bb3adcb3e17 to your computer and use it in GitHub Desktop.
Save PramodDutta/0026d80c26ce4141e06e0bb3adcb3e17 to your computer and use it in GitHub Desktop.

String slicing - TheTestingAcademy

String slicing in Python allows you to extract a part (substring) of a string by specifying a start and end index, and optionally a step. This feature is very versatile and can be used for various purposes, such as extracting substrings, reversing strings, and more. Here's an overview of how string slicing works, including the syntax and some examples:

Syntax

The basic syntax for string slicing is:

string[start:stop:step]
  • start (optional): The starting index of the substring. If omitted, it defaults to 0, meaning the beginning of the string.
  • stop (optional): The ending index of the substring. This index is not included in the substring. If omitted, it defaults to the length of the string, meaning the end of the string.
  • step (optional): The step size. If omitted, it defaults to 1. A step size of 2 means every second character is included in the substring, and so on. A negative step size can be used to reverse the string.

Examples

Here are some examples demonstrating string slicing in Python:

  1. Extracting a Substring:
s = "Hello, World!"
print(s[7:12])  # World
  1. Omitting Start and End:
# Omitting both start and end
print(s[:])  # Hello, World!

# Omitting start
print(s[:5])  # Hello

# Omitting end
print(s[7:])  # World!
  1. Using Negative Indices:
# Starting from the end
print(s[-6:-1])  # World
  1. Step Size:
# Every second character
print(s[::2])  # Hlo ol!

# Reversing a string
print(s[::-1])  # !dlroW ,olleH
  1. Negative Step Size:
# Reverse substring
print(s[12:6:-1])  # !dlroW

Notes

  • If start is greater than the length of the string, the result will be an empty string.
  • If stop is specified as a larger value than the string length, Python will use the length of the string.
  • The step value cannot be 0; it raises a ValueError.

String slicing is a powerful and efficient way to manipulate strings in Python, enabling concise and readable code for string processing tasks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment