Skip to content

Python trim first and last character | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading