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"