Python trim first and last character | Example code

Use the slice notation [ ] with 1:-1 as an argument to trim the first and last character. Where 1 represents the second character index (included) and -1 represents the last character index (excluded).

string[1:-1]

Example trim the first and last character from a string in Python

Simple example code.

str1 = "Hello world!"

print(str1[1:-1])

Output:

Python trim first and last character

Note: There are two types of indexes in python:-

  • Left to right or Positive Index
  • Right to left or Negative Index

Do comment if you have any doubts and suggestions on this Python string trim topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.