How to Remove the Last N Characters from a String in Python?

Estimated read time 1 min read

To remove the last N characters from a string in Python, you can use string slicing. Here is an example code snippet that removes the last N characters from a string:

original_string = "Hello, World!"

# Remove the last 4 characters from the string
new_string = original_string[:-4]

print(new_string)  # Output: "Hello, W"

In this code, we define an original string (original_string) that contains characters.

Next, we create a new string (new_string) by slicing the original string up to the N-th last character. The [:-N] syntax is used to slice the string up to the N-th last character.

Finally, we print the new string (new_string) that contains the original string with the last N characters removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply