🔍 String Indexing & Slicing

Last Updated: 10th August 2025


📌 1. Indexing in Strings

  • Indexing means accessing individual characters in a string.
  • Index starts from 0 (left to right).
  • You can also use negative indexing (right to left, starting from -1).
  • e.g. a = "Hello World!", see a visual below

string_variable

Syntax:

string_variable[index]

Hinglish Tip 🗣: Indexing ka matlab hai string ke andar ek specific position par character ko access karna.

Example:

a = "Hello World!"
print(a[0])   # Output: 'H' (first character)
print(a[-1])  # Output: '!' (last character using negative indexing)
print(a[3])   # Output: 'l' (fourth character)
print(a[5])   # Output: ' ' (sixth character i.e. space)

📌 2. Slicing in Strings

  • Slicing means extracting a portion of a string.
  • It allows you to select a range of characters from a string.

Hinglish Tip 🗣: Slicing me hum ek part (substring) nikalte hain. End index par wala character include nahi hota. Step ka use skipping ke liye hota hai.

Syntax:

string_variable[start_index : end_index : step]

Here,

  • start_index → starting index (included)
  • end_index → ending index (excluded)
  • step → jump value (default is 1)

Example:

text = "Python"
print(text[0:4])    # Pyth (0 to 3)
print(text[2:])     # thon (from index 2 to end)
print(text[:3])     # Pyt  (start to index 2)
print(text[::2])    # Pto  (every 2nd character)
print(text[::-1])   # nohtyP (reversed string)

💡 Quick Practice

  1. Take "Programming" and print only "Pro".
  2. Print the last 4 characters of "Developer".
  3. Reverse the string "Python" using slicing.
  4. Print every 2nd character of "DataScience".