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.
1represents second character index (included).
-1represents last character index (excluded) .
Here is an example:
str = "How are you" print(str[1:-1])
"ow are yo"
Alternatively, we can also use the
rstrip() methods like this
str = "How are you" strippedString = str.lstrip("H").rstrip("u") print (strippedString) # "ow are yo"
name = "/apple/" strippedString = name.lstrip("/").rstrip("/") print(strippedString) # "apple"