w3resource

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:

Flowchart: Python - Remove the first and last elements from a given string.

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:

Flowchart: Python - Remove the first and last elements from a given string.

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.



Follow us on Facebook and Twitter for latest update.