Languages
[Edit]
EN

Python - remove last character from string

0 points
Created by:
Dale-K1
417

In this article, we would like to show you how to remove last character from the string in Python.

Quick solution:

text = "ABC"
result = text[:-1]
print("after: ", result)  # AB

or:

text = "ABC"
result = text[:len(text) - 1]
print("after: ", result)  # AB

 

Overview

string[start_index: end_index]

Where:

  • start_index -  index position, from where it will start fetching the characters (default value is 0),
  • end_index -  index position, where it will end fetching the characters (default value is end of the string),

We also use len() function to get the string length.

Practical examples

1. Slicing with positive indexing

In this example, we use slicing with positive indexing to remove the last character from a string.

text = "dirask"

print("String before:", text)

# remove last character from string
text = text[:len(text) - 1]

print("String after: ", text)

Output:

String before: dirask
String after:  diras

2. Slicing with negative indexing

In this example, we use slicing with negative indexing to remove the last character from the string.

text = "dirask"

print("String before:", text)

# remove last character from a string
text = text[:-1]

print("String after: ", text)

Output:

String before: dirask
String after:  diras
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - remove last character from string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join