Practical 5: Program to Demonstrate Slice Operation on String Objects.
Problem Statement
Write a Python program to demonstrate slice operations on string objects.
The program should:
- Accept a string as input from the user.
- Perform slicing operations to extract specific parts of the string.
- Display the results of various slicing techniques.
Solution Code
# Program to demonstrate slice operation on string objects
# Taking input from the user
string = input("Enter a string: ")
# Performing different slicing operations
first_five_chars = string[:5] # Extracts the first five characters
last_five_chars = string[-5:] # Extracts the last five characters
middle_part = string[2:7] # Extracts characters from index 2 to 6
every_second_char = string[::2] # Extracts every second character
reversed_string = string[::-1] # Reverses the string
# Displaying results
print("First 5 characters:", first_five_chars)
print("Last 5 characters:", last_five_chars)
print("Middle part (index 2 to 6):", middle_part)
print("Every second character:", every_second_char)
print("Reversed string:", reversed_string)
Expected Outcome
- The program takes a string input from the user.
- It extracts and displays specific slices of the string.
- The output shows different slicing operations applied to the string.
Enter a string: Hello World
First 5 characters: Hello
Last 5 characters: World
Middle part (index 2 to 6): llo W
Every second character: HloWrd
Reversed string: dlrow olleH
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 3 Practical 5 solution where we have written Python program to demonstrate slice operations on string objects.
- Taking Input from the User:
- The input() function is used to accept a string from the user.
- Performing Slice Operations:
- string[:5] → Extracts the first five characters.
- string[-5:] → Extracts the last five characters.
- string[2:7] → Extracts characters from index 2 to 6.
- string[::2] → Extracts every second character (skipping one character).
- string[::-1] → Reverses the string.
- Displaying the Results:
- The extracted portions are printed using print() statements.
Key Concepts Learned
- String Slicing ([:])
- Allows extracting portions of a string using start, stop, and step values.
- Negative Indexing (-1)
- Helps access characters from the end of a string.
- String Reversal Using [::-1]
- A simple way to reverse a string in Python.