In the previous section, you learned about Python recursion and how functions can solve problems by calling themselves. Before moving into more advanced text processing, it is important to understand how Python stores and accesses characters inside a string.
Every string in Python is a sequence of characters. Each character occupies a specific position called an index. Python allows you to access any individual character using its index, making it easy to retrieve, process, and manipulate text.
Understanding string indexing is one of the most fundamental skills in Python programming because strings are widely used in data analysis, web development, automation, machine learning, and software development.
In this lesson, you will learn how Python string indexing works, explore positive and negative indexing, access individual characters, understand string immutability, and avoid common indexing mistakes.
After completing this lesson, you will be able to:
A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
A string can contain letters, numbers, symbols, spaces, and special characters.
language = "Python"
city = 'Dehradun'
course = "Data Analytics"
message = """Welcome to
Vista Academy"""
Each character inside a string has its own position, which Python identifies using an index.
Consider the following string:
language = "Python"
Python stores each character separately.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
Python automatically assigns both positive and negative index numbers to every character.
String indexing is the process of accessing individual characters in a string using their index position.
Index values are written inside square brackets ([]).
string_name[index]
language = "Python"
print(language[0])
Output
P
The index 0 refers to the first character.
Positive indexing starts from the beginning of the string.
The first character has index 0, the second character has index 1, and so on.
language = "Python"
print(language[0])
print(language[2])
print(language[5])
Output
P
t
n
Python counts characters from left to right when using positive indexing.
Negative indexing starts from the end of the string.
The last character always has the index -1.
language = "Python"
print(language[-1])
print(language[-2])
print(language[-6])
Output
n
o
P
Negative indexing is useful when you want to access characters near the end of a string.
You can retrieve any character by specifying its index.
course = "Python Programming"
print(course[0])
print(course[7])
print(course[-1])
Output
P
P
g
Every character, including spaces, has its own index.
Spaces and punctuation marks are treated as ordinary characters.
text = "Hello World!"
print(text[5])
print(text[-1])
Output
!
The character at index 5 is a space, while the last character is an exclamation mark.
Python strings are immutable, which means individual characters cannot be changed after the string is created.
language = "Python"
language[0] = "J"
Output
TypeError: 'str' object does not support item assignment
Instead of modifying individual characters, you must create a new string.
language = "Python"
language = "J" + language[1:]
print(language)
Output
Jython
If you try to access an index that does not exist, Python raises an IndexError.
language = "Python"
print(language[10])
Output
IndexError: string index out of range
Always ensure that the index is within the valid range of the string.
Suppose you want to display the first letter of a student’s name.
student = "Rahul"
print("First Letter:", student[0])
print("Last Letter:", student[-1])
Output
First Letter: R
Last Letter: l
Indexing makes it easy to retrieve specific characters from user input or stored data.
The first character is always at index 0, not 1.
Accessing an index outside the string length results in an IndexError.
Positive indexes count from the beginning, while negative indexes count from the end.
Strings are immutable, so characters cannot be changed using indexing.
Spaces, punctuation marks, and special symbols all have their own index positions.
In this section, you learned how Python stores strings as sequences of characters and how each character has both a positive and a negative index. You explored positive indexing, negative indexing, accessing individual characters, string immutability, and the IndexError exception. You also reviewed common beginner mistakes and learned why indexing is essential for text processing. In the next section, you will explore Python String Slicing, where you will learn how to extract portions of strings using start, stop, and step values, reverse strings, perform negative slicing, and solve practical text-processing problems.
In the previous section, you learned how to access individual characters in a string using positive and negative indexing. While indexing retrieves a single character, Python also allows you to extract multiple characters from a string. This process is called string slicing.
String slicing is one of the most frequently used features in Python because it allows you to extract words, substrings, file extensions, dates, usernames, and many other pieces of text without modifying the original string.
In this section, you will learn the syntax of string slicing, understand the start, stop, and step parameters, reverse strings, perform negative slicing, and solve practical examples.
String slicing is the process of extracting a portion of a string by specifying a range of indexes.
Unlike indexing, which returns a single character, slicing returns a new string containing multiple characters.
string[start : stop : step]
There are three parts in slicing:
Consider the following string.
language = "Python"
You can extract part of the string using slicing.
print(language[0:4])
Output
Pyth
The slice starts from index 0 and stops before index 4.
The start index specifies where Python begins extracting characters.
language = "Python"
print(language[2:6])
Output
thon
The slice begins at index 2, which contains the character t.
The stop index specifies where slicing ends.
The character at the stop index is not included in the result.
language = "Python"
print(language[1:5])
Output
ytho
The slice stops before index 5.
If the start index is omitted, Python starts from the beginning of the string.
language = "Python"
print(language[:4])
Output
Pyth
If the stop index is omitted, Python extracts characters until the end of the string.
language = "Python"
print(language[2:])
Output
thon
If both start and stop indexes are omitted, the entire string is returned.
language = "Python"
print(language[:])
Output
Python
This is commonly used when creating a copy of a string.
The step value determines how many characters Python skips while slicing.
language = "Python"
print(language[0:6:2])
Output
Pto
Python selects every second character.
text = "DataAnalytics"
print(text[::3])
Output
Daay
The step value of 3 selects every third character.
A negative step value reverses the string.
language = "Python"
print(language[::-1])
Output
nohtyP
This is one of the most commonly used slicing techniques in Python.
Negative indexes can also be used while slicing.
language = "Python"
print(language[-4:-1])
Output
tho
The slice begins at index -4 and stops before -1.
language = "Python"
print(language[-1:-7:-2])
Output
nhy
Python starts from the last character and moves backward by two positions each time.
course = "Programming"
print(course[:4])
Output
Prog
course = "Programming"
print(course[-3:])
Output
ing
text = "Python Programming"
print(text[::2])
Output
Pto rgamn
text = "Python"
print(text[::-2])
Output
nhy
Consider the following program.
language = "Python"
result = language[1:5]
print(result)
Execution Steps
"Python".1.1, 2, 3, and 4.5 is excluded.result.Output
ytho
The stop index is always excluded from the sliced result.
Indexing returns one character, while slicing returns a substring.
A step value of 0 is invalid and raises a ValueError.
Ensure that the slicing direction matches the step value.
Slicing never modifies the original string because strings are immutable.
In this section, you learned how Python string slicing extracts portions of a string using the start, stop, and step parameters. You explored basic slicing, omitting indexes, step values, reversing strings, negative slicing, and practical text extraction techniques. You also followed the execution flow of slicing operations and reviewed common beginner mistakes. In the next section, you will apply string indexing and slicing to real-world problems such as extracting names, email domains, file extensions, dates, masking sensitive information, checking palindromes, and processing text efficiently.
String indexing and slicing are used extensively in real-world Python applications. Whether you are processing names, extracting domains from email addresses, identifying file extensions, masking sensitive information, or validating user input, indexing and slicing provide simple and efficient solutions.
In this section, you will explore practical examples that demonstrate how string indexing and slicing are applied to everyday programming tasks.
Suppose a full name contains the first name followed by the last name.
full_name = "Rahul Sharma"
first_name = full_name[:5]
print(first_name)
Output
Rahul
Slicing extracts only the required portion of the string.
You can extract the domain name using string methods and slicing.
email = "student@gmail.com"
position = email.index("@")
domain = email[position + 1:]
print(domain)
Output
gmail.com
This technique is commonly used in email validation systems.
The following program extracts the extension from a file name.
filename = "report.pdf"
position = filename.index(".")
extension = filename[position + 1:]
print(extension)
Output
pdf
This is useful when processing uploaded files.
One of the easiest ways to reverse a string is by using slicing.
language = "Python"
print(language[::-1])
Output
nohtyP
The negative step value reverses the string.
A palindrome reads the same forwards and backwards.
word = "madam"
if word == word[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Output
Palindrome
String slicing provides a simple way to compare a string with its reversed version.
Suppose the date is stored in the format YYYY-MM-DD.
date = "2026-08-06"
year = date[:4]
month = date[5:7]
day = date[8:]
print("Year :", year)
print("Month:", month)
print("Day :", day)
Output
Year : 2026
Month: 08
Day : 06
This approach is commonly used when processing formatted dates.
You can hide sensitive digits using slicing.
mobile = "9876543210"
masked = "******" + mobile[-4:]
print(masked)
Output
******3210
Only the last four digits remain visible.
The step parameter makes it easy to select alternate characters.
text = "Python Programming"
print(text[::2])
Output
Pto rgamn
Python skips every second character.
The username is the portion before the @ symbol.
email = "rahul@gmail.com"
position = email.index("@")
username = email[:position]
print(username)
Output
rahul
This technique is useful in user authentication systems.
The following program displays the initials of a person’s name.
name = "Rahul Sharma"
parts = name.split()
initials = parts[0][0] + "." + parts[1][0]
print(initials)
Output
R.S
Indexing retrieves the first character of each word.
Consider the following program.
text = "Programming"
result = text[3:8]
print(result)
Execution Steps
"Programming".3.3, 4, 5, 6, and 7 are selected.8 is excluded.result.Output
gramm
Choose descriptive names such as first_name, domain, extension, and username.
Negative indexes simplify access to characters near the end of a string.
When possible, use string methods like index() or find() instead of assuming fixed positions.
Slicing is shorter, faster, and easier to read for extracting substrings.
Slicing creates a new string instead of modifying the original one.
In this section, you learned how Python string indexing and slicing are applied to practical tasks such as extracting names, email domains, usernames, file extensions, date components, masking mobile numbers, reversing strings, checking palindromes, displaying initials, and selecting alternate characters. You also explored best practices for writing clean string-processing code and reviewed common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python String Methods.
In this lesson, you learned how Python stores strings as sequences of characters and how each character can be accessed using its index position. You explored both positive and negative indexing, allowing you to retrieve characters from the beginning or the end of a string efficiently.
You also learned how string slicing extracts portions of a string using the start, stop, and step parameters. You discovered how to omit indexes, reverse strings using negative steps, and extract substrings for practical applications such as names, email addresses, dates, and file extensions.
Through practical examples, you applied indexing and slicing to real-world programming tasks including extracting usernames, masking mobile numbers, checking palindromes, reversing strings, and processing formatted text.
Mastering string indexing and slicing provides a strong foundation for learning advanced string manipulation techniques and text processing in Python.
0.-1.[::-1] reverses a string.String indexing is the process of accessing an individual character in a string using its position.
Indexing returns a single character, while slicing returns a substring containing multiple characters.
Positive indexing starts from the beginning of the string, where the first character has index 0.
Negative indexing starts from the end of the string, where the last character has index -1.
No. The stop index is always excluded from the sliced result.
Use string[::-1] to reverse a string.
No. Python strings are immutable, so individual characters cannot be modified directly.
Python raises an IndexError when an index is outside the valid range of the string.
Create a Python program that extracts useful information from user input using string indexing and slicing.
Your program should:
Enter Name: Rahul Sharma
First Character : R
Last Character : a
Enter Email: rahul@gmail.com
Username : rahul
Domain : gmail.com
Enter File Name: report.pdf
Extension : pdf
Enter Mobile Number: 9876543210
Masked Number : ******3210
Enter Word: madam
Reversed Word : madam
Palindrome : True
Congratulations! You have successfully learned Python String Indexing and Slicing. You now understand how to access characters using positive and negative indexing, extract substrings with slicing, use the start, stop, and step parameters, reverse strings, and apply these concepts to real-world text-processing tasks.
In the next lesson, you will learn Python String Methods: Complete Guide for Beginners. You will explore built-in string methods such as upper(), lower(), strip(), replace(), split(), join(), find(), count(), startswith(), endswith(), and many more to efficiently manipulate and analyze text in Python.