Practical 6: Program to demonstrate how characters in a string can be accessed using negative indexing.
Problem Statement
Write a Python program to demonstrate how characters in a string can be accessed using negative indexing.
The program should:
- Accept a string from the user.
- Access and display specific characters using negative indexes.
- Demonstrate how negative indexes work in Python.
Solution Code
# Program to understand how characters in a string are accessed using negative indexes
# Taking input from the user
string = input("Enter a string: ")
# Accessing characters using negative indexes
last_char = string[-1] # Last character
second_last_char = string[-2] # Second last character
third_last_char = string[-3] # Third last character
first_char = string[-len(string)] # First character using negative index
# Displaying results
print("Last character:", last_char)
print("Second last character:", second_last_char)
print("Third last character:", third_last_char)
print("First character using negative indexing:", first_char)
Output
The program takes a string input from the user.
- It accesses specific characters using negative indexes.
- The output shows the extracted characters based on negative indexing.
Example output:
Enter a string: Hello World
Last character: d
Second last character: l
Third last character: r
First character using negative indexing: H
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 3 Practical 6 solution where we have written Python program to demonstrate how characters in a string can be accessed using negative indexing.
- Taking Input from the User:
- The input() function is used to accept a string.
- Accessing Characters Using Negative Indexing:
- string[-1] → Retrieves the last character.
- string[-2] → Retrieves the second last character.
- string[-3] → Retrieves the third last character.
- string[-len(string)] → Retrieves the first character using a negative index.
- Displaying the Results:
- The extracted characters are printed using print() statements.
Key Concepts Learned
- Negative Indexing in Strings (-1, -2, -3, …)
- Allows accessing characters from the end of a string.
- Retrieving the First Character Using -len(string)
- Demonstrates an alternate way of getting the first character.
- Difference Between Positive and Negative Indexing
- Positive indexes count from left to right (0 to n-1).
- Negative indexes count from right to left (-1 to -n).