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 represents second character index (included).
  • -1 represents last character index (excluded) .

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 - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course