by Sai gowtham

Removing the first and last character from a string in Python

Learn, how to remove the first and last character from a given string in Python.

We can remove the first and last character of a string by using the slice notation [ ] with 1:-1 as an argument.

  • 1 removes the first character.
  • -1 removes the last character.

Here is an example:

str = "How are you"

print(str[1:-1])

Output:

"ow are yo"

Alternatively, we can also use the lstrip() and rstrip() methods like this

str = "How are you"

strippedString = str.lstrip("H").rstrip("u")

print (strippedString) # "ow are yo"

Another example:

name = "/apple/"
strippedString = name.lstrip("/").rstrip("/")

print(strippedString) #  "apple"

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course