Online Tutorials & Training Materials | STechies.com
Register Login

Remove First and Last Character from String in Python

|| 0

Remove First and Last Character from String in Python
Stechies

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

In Python each character of string has its own 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 string.

Remove Last Character from string

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

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