Popular Searches
Popular Course Categories
Popular Courses

Using String Slicing and Indexing

Using String Slicing and Indexing

Python Data Structures — Strings, Lists, and Tuples

Using String Slicing and Indexing in Python

Course: Python Training

Topic: Using String Slicing and Indexing

Course Link: Python Training Course

Demo Registration: Register for a Course Demo

Academy Website: JustAcademy


1. Introduction to String Indexing and Slicing

Strings are one of the most commonly used data types in Python. A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Python provides indexing and slicing to access individual characters or extract portions of a string.

String indexing allows you to access a single character by specifying its position. String slicing allows you to extract a substring by specifying a range of positions.

These operations are useful for processing names, extracting parts of email addresses, reading codes, manipulating text, validating input, and preparing data for analysis.

language = "Python"

print(language[0])
print(language[1:4])

Output:

P
yth

The expression language[0] retrieves the first character, while language[1:4] extracts the characters at positions 1, 2, and 3.

2. Learning Objectives

  • Understand how Python strings are indexed.
  • Learn positive and negative indexing.
  • Extract substrings using slicing.
  • Understand the start, stop, and step parameters.
  • Use slicing to reverse strings and select characters at intervals.
  • Recognize indexing errors and handle boundary conditions.
  • Understand string immutability.
  • Apply slicing and indexing to practical text-processing problems.

3. Understanding String Indexing

Indexing refers to accessing a specific character in a string using square brackets []. Python uses zero-based indexing, which means the first character has index 0, the second has index 1, and so on.

Example

word = "Python"

print(word[0])
print(word[1])
print(word[2])
print(word[3])
print(word[4])
print(word[5])

Output:

P
y
t
h
o
n

The string "Python" contains six characters. Its valid positive indices range from 0 to 5.

Index Position Table

Character P y t h o n
Positive Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1

The last valid positive index is always len(string) - 1. For a non-empty string, the first character can also be accessed using the index -len(string).

4. Positive Indexing

Positive indexing starts at zero and moves from left to right. It is useful when you know the position of the character you want to access.

Example 1: Accessing Characters

message = "Welcome"

print(message[0])
print(message[3])
print(message[6])

Output:

W
c
e

Example 2: Using len() with Indexing

The built-in len() function returns the number of characters in a string.

text = "Python Programming"

print("Length:", len(text))
print("First character:", text[0])
print("Last character:", text[len(text) - 1])

Output:

Length: 18
First character: P
Last character: g

Using len(text) - 1 helps calculate the final valid positive index. Remember that spaces also count as characters.

5. Negative Indexing

Negative indexing allows you to access characters from the end of a string. The index -1 refers to the last character, -2 refers to the second-last character, and the count continues toward the beginning.

Example

language = "Python"

print(language[-1])
print(language[-2])
print(language[-3])
print(language[-6])

Output:

n
o
h
P

Negative indexing is particularly helpful when you need the last character or a suffix without calculating the string length manually.

Practical Example: Getting a File Extension

filename = "report.pdf"

print(filename[-3:])

Output:

pdf

This example extracts the last three characters. It is suitable for illustrating slicing, but it is not a complete file-extension validation method because file extensions can have different lengths and filenames can have special cases.

6. What Is String Slicing?

String slicing extracts a portion of a string and returns it as a new string. Instead of selecting only one character, slicing allows you to select a range of characters.

Basic Syntax

string[start:stop]
  • start: The index where extraction begins. This position is included.
  • stop: The index where extraction ends. This position is excluded.

Example

word = "Python"

print(word[0:3])
print(word[2:5])
print(word[1:4])

Output:

Pyt
tho
yth

For word[2:5], Python includes indices 2, 3, and 4, but excludes index 5. Therefore, the result is "tho".

7. Understanding the Start and Stop Positions

The stop position in a slice is exclusive. This design makes it easy to calculate the number of selected characters when the indices are within the string's normal range.

text = "Computer"

print(text[0:4])
print(text[4:8])
print(text[0:8])

Output:

Comp
uter
Computer

The first slice selects four characters, the second selects four more, and the third selects the complete string.

A useful property is that a string can be divided into two slices and recombined without losing characters:

word = "Python"

print(word[:2] + word[2:])

Output: Python

In general, text[:index] + text[index:] reproduces the original string.

8. Omitting Start or Stop Values

Python allows you to omit the start or stop value in a slice. If the start is omitted, slicing begins at the beginning of the string. If the stop is omitted, slicing continues to the end.

Expression Meaning Example Result
text[:3] Beginning up to, but not including, index 3. "Pyt"
text[2:] Index 2 through the end. "thon"
text[:] The entire string. "Python"
text[-3:] The last three characters. "hon"
text[:-2] Everything except the last two characters. "Pyth"

Example

text = "Python"

print(text[:3])
print(text[3:])
print(text[:])
print(text[-3:])
print(text[:-2])

Output:

Pyt
hon
Python
hon
Pyth

9. Slicing with Negative Indices

Slicing can use negative indices to select characters relative to the end of a string. This is especially useful for extracting suffixes or removing a fixed number of trailing characters.

Example

text = "Programming"

print(text[-3:])
print(text[-6:-2])
print(text[:-4])
print(text[-8:-3])

Output:

ing
ramm
Program
gramm

Negative slice positions follow the same rule as positive positions: the start is included and the stop is excluded. If the start position is not before the stop position for a forward slice, the result is usually an empty string.

10. Using the Step Parameter

Python slicing supports an optional third parameter called step. It controls how many positions to move between selected characters.

Syntax

string[start:stop:step]
  • start: Starting position.
  • stop: Ending boundary, which is excluded.
  • step: The interval between selected positions.

The default step is 1. A positive step moves from left to right, while a negative step moves from right to left.

Example 1: Selecting Every Second Character

text = "abcdefgh"

print(text[::2])
print(text[1::2])

Output:

aceg
bdfh

The first expression selects characters at indices 0, 2, 4, and 6. The second starts at index 1 and selects indices 1, 3, 5, and 7.

Example 2: Selecting a Range with a Step

numbers = "0123456789"

print(numbers[1:8:2])
print(numbers[::3])

Output:

1357
0369

11. Reversing a String with Slicing

One of the most common uses of slicing is reversing a string. Using a step of -1 makes Python traverse the string from right to left.

Example

word = "Python"

reversed_word = word[::-1]

print(reversed_word)

Output:

nohtyP

The expression word[::-1] omits the start and stop boundaries and uses a negative step. Python begins at the end and selects characters in reverse order.

Practical Example: Checking a Simple Palindrome

A palindrome is text that reads the same forward and backward under a chosen comparison rule. For a simple exact comparison:

word = "level"

if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

Output:

Palindrome

This example is case-sensitive and does not ignore spaces or punctuation. For natural-language phrases, normalize the text before comparing it.

12. Indexing vs. Slicing

Feature Indexing Slicing
Purpose Retrieves one character. Retrieves a substring.
Syntax text[index] text[start:stop:step]
Return value A one-character string for a valid character index. A string containing the selected characters.
Out-of-range positions An invalid index raises IndexError. Out-of-range slice boundaries are generally handled by clipping them to the sequence boundaries.
Step parameter Not used. Optional.
Example "Python"[0] returns "P". "Python"[1:4] returns "yth".

13. Understanding IndexError

An IndexError occurs when indexing attempts to access a position outside the valid range of a sequence.

Incorrect Example

word = "Python"

print(word[6])

This raises an IndexError because the valid positive indices are 0 through 5.

Correct Example

word = "Python"

if len(word) > 6:
    print(word[6])
else:
    print("Index is outside the valid range")

Output:

Index is outside the valid range

Checking the string length before indexing helps prevent errors when the length or content of the input is unknown.

Out-of-Range Slicing

word = "Python"

print(word[2:100])
print(word[100:])
print(word[-100:3])

Output:

thon

Pyt

Unlike direct indexing, slicing normally handles boundaries outside the string by limiting the slice to available characters. A slice can also return an empty string when no characters match the specified range.

14. Strings Are Immutable

Python strings are immutable, which means their individual characters cannot be changed in place after the string has been created. Indexing can read a character, but it cannot be used to assign a replacement character.

Incorrect Example

word = "Python"
word[0] = "J"

This raises a TypeError because string items do not support assignment.

Correct Example: Creating a New String

word = "Python"
new_word = "J" + word[1:]

print(new_word)

Output:

Jython

The original string remains unchanged. A new string is created by combining the replacement character with the slice containing the remaining characters.

15. Practical Applications of String Slicing and Indexing

15.1 Extracting a Username from an Email Address

email = "[email protected]"
position = email.find("@")

if position != -1:
    username = email[:position]
    print(username)
else:
    print("Invalid email format")

Output:

student

The find() method locates the first occurrence of @. Slicing extracts everything before it. This is a simple demonstration and does not perform complete email-address validation.

15.2 Extracting a Domain from an Email Address

email = "[email protected]"
position = email.find("@")

if position != -1:
    domain = email[position + 1:]
    print(domain)

Output:

example.com

15.3 Extracting a Year from a Date String

date = "2026-10-22"

year = date[:4]
month = date[5:7]
day = date[8:10]

print("Year:", year)
print("Month:", month)
print("Day:", day)

Output:

Year: 2026
Month: 10
Day: 22

This approach assumes the date follows the exact YYYY-MM-DD format. For general date handling, Python's datetime module is more suitable.

15.4 Masking a Phone Number

phone = "9876543210"

masked_phone = "*" * (len(phone) - 4) + phone[-4:]

print(masked_phone)

Output:

******3210

The slice phone[-4:] extracts the final four characters. The remaining positions are represented by asterisks.

15.5 Extracting a Short Preview

description = "Python is useful for automation and data analysis."

preview = description[:20]

print(preview)

Output:

Python is useful for

This technique can be used to create short previews of longer text. If the original text must be indicated as truncated, the program can append an ellipsis when the length exceeds the limit.

16. Combining Indexing, Slicing, and String Methods

Indexing and slicing are often combined with string methods such as lower(), upper(), strip(), and replace() to process text.

Example: Cleaning and Extracting Text

text = "  PYTHON PROGRAMMING  "

clean_text = text.strip().lower()
first_word = clean_text[:6]
last_word = clean_text[7:]

print(clean_text)
print(first_word)
print(last_word)

Output:

python programming
python
programming

The strip() method removes surrounding whitespace, and lower() converts letters to lowercase. Slicing then extracts the desired portions.

Note: Fixed slice positions depend on the structure of the text. For general text with variable word lengths, use methods such as split() rather than relying on fixed positions.

17. Common Mistakes and Best Practices

Mistake Why It Happens Best Practice
Using index 1 for the first character Confusing zero-based indexing with one-based counting. Remember that the first index is 0.
Including the stop index mentally Forgetting that the slice stop boundary is excluded. Use examples to verify which characters are selected.
Using an invalid index The index is negative beyond the valid range or greater than the last index. Check the string length before indexing.
Expecting a slice to change the original string Assuming slicing modifies a string in place. Assign the result to a variable when you need to keep it.
Using a zero step A slice step of zero is not allowed. Use a non-zero positive or negative step.
Incorrect reverse slicing Using the wrong direction or incompatible start and stop positions. Use text[::-1] for a complete reversal.
Relying on fixed positions in variable text The string format may change. Use string methods, parsing functions, or regular expressions where appropriate.

18. Practice Exercises

Exercise 1: Basic Indexing

Given word = "Programming", print the first character, fourth character, and last character.

Exercise 2: Positive Slicing

Extract "gram" from the string "Programming" using slicing.

Exercise 3: Negative Indexing

Print the last two characters of "Developer" using negative indexing and slicing.

Exercise 4: Reverse a String

Reverse the string "Python" using slicing.

Exercise 5: Select Alternate Characters

Use slicing to select every second character from "abcdefghij", starting at the first character.

Exercise 6: Extract a Username

Given "[email protected]", extract the part before @.

Exercise 7: Check a Palindrome

Use slicing to check whether the word "madam" is a palindrome.

19. Practice Exercise Solutions

Solution 1

word = "Programming"

print(word[0])
print(word[3])
print(word[-1])

Output:

P
g
g

Solution 2

word = "Programming"
print(word[3:7])

Output: gram

Solution 3

word = "Developer"
print(word[-2:])

Output: er

Solution 4

word = "Python"
print(word[::-1])

Output: nohtyP

Solution 5

text = "abcdefghij"
print(text[::2])

Output: acegi

Solution 6

email = "[email protected]"
position = email.find("@")

if position != -1:
    print(email[:position])

Output: learner

Solution 7

word = "madam"

if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

Output: Palindrome

20. Interview Questions and Answers

Q1. What is string indexing in Python?

Answer: String indexing accesses an individual character using its position inside square brackets. Python uses zero-based indexing.

Q2. What is string slicing?

Answer: String slicing extracts a portion of a string using a start position, stop boundary, and optional step.

Q3. What is the difference between positive and negative indexing?

Answer: Positive indexing counts from the beginning starting at 0, while negative indexing counts from the end starting at -1.

Q4. Why is the stop index excluded in slicing?

Answer: An exclusive stop boundary makes slice lengths easier to calculate and allows adjacent slices such as s[:i] and s[i:] to partition a string without overlap.

Q5. What does text[::-1] do?

Answer: It returns a reversed version of the string by using a step of -1.

Q6. What happens when an invalid index is used?

Answer: Direct indexing with an out-of-range position raises IndexError. Slicing generally handles out-of-range boundaries without raising that error.

Q7. Can a string be modified through indexing?

Answer: No. Strings are immutable. A modified result must be created as a new string.

Q8. How can you obtain the last character of a string?

Answer: Use text[-1] for a non-empty string.

Q9. How do you extract the last three characters?

Answer: Use text[-3:]. If the string has fewer than three characters, the slice returns the available characters.

Q10. What does the step parameter do?

Answer: The step determines the interval between selected characters. A positive step moves forward, while a negative step moves backward.

21. Quick Revision Checklist

  • Python strings are sequences of characters.
  • Positive indexing begins at 0.
  • Negative indexing begins at -1 from the end.
  • Indexing retrieves one character.
  • Slicing extracts a substring.
  • The start boundary is included, and the stop boundary is excluded.
  • Omitting the start or stop uses the relevant string boundary by default.
  • The third slice parameter controls the step.
  • text[::-1] reverses a string.
  • Direct indexing outside the valid range raises IndexError.
  • Strings are immutable, so character replacement creates a new string.
  • Slicing is useful for extracting, transforming, and analyzing text.

22. Conclusion

String indexing and slicing are essential Python techniques for accessing and processing text. Indexing retrieves individual characters, while slicing extracts portions of strings using start, stop, and step values. Negative indices make it easy to access characters from the end, and reverse slicing provides a concise way to reverse a string.

Practise these techniques with different string lengths, empty strings, negative indices, and boundary values. Combining indexing and slicing with string methods will help you build effective text-processing programs.


Learn Python with JustAcademy

Continue learning Python and strengthen your programming fundamentals with these resources.

whatsapp