Python: Remove the first and last elements from a given string
Python Basic - 1: Exercise-123 with Solution
Write a Python program to remove the first and last elements from a given string.
Sample Solution-1:
Python Code:
def test(str):
return str if len(str) < 3 else str[1:-1]
str = "PHP"
print("Original string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
str = "Python"
print("\nOriginal string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
str = "JavaScript"
print("\nOriginal string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
Sample Output:
Original string: PHP Removing the first and last elements from the said string: H Original string: Python Removing the first and last elements from the said string: ytho Original string: JavaScript Removing the first and last elements from the said string: avaScrip
Flowchart:

Sample Solution-2:
Python Code:
def test(str):
return str[1:-1] if len(str) > 2 else str
str = "PHP"
print("Original string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
str = "Python"
print("\nOriginal string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
str = "JavaScript"
print("\nOriginal string: ",str)
print("Removing the first and last elements from the said string: ",test(str))
Sample Output:
Original string: PHP Removing the first and last elements from the said string: H Original string: Python Removing the first and last elements from the said string: ytho Original string: JavaScript Removing the first and last elements from the said string: avaScrip
Flowchart:

Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to check if a given string contains only lowercase or uppercase characters.
Next: Write a Python program to check if a given string contains two similar consecutive letters.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join