Online Tutorials & Training Materials | STechies.com
Register Login

Python Remove last Character from String

12 Aug 2019 1:01 pm || 0

Remove First and Last Character from String

In this tutorial, you will learn how to remove the first and last character from string using an index.

In Python, each character of the string has its index. There are two types of indexes in python:

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

string

s

t

e

c

h

i

e

s

index

0

1

2

3

4

5

6

7

index

-8

-7

-6

-5

-4

-3

-2

-1

By using the string index, we can remove specific characters from the string.

Remove last Character from String Python

Example:

# Python3 code to remove last character from string
# initializing test string
string='stechies'

# Remove last character
remove_last = string[:-1]

# Print remaining string
print(remove_last)

Output:

stechie

Python Remove first Character from String

Example:

# Python3 code to remove first character from string
# initializing test string
string='stechies'

# Remove first character
remove_first = string[1:]

# Print remaining string
print(remove_first)

Output:

techies