

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I remove a substring from the end of a string in Python?
If you want to remove a substring from the end of a string, you should fisrt check if the string ends with that substring. If it does, then slice the string keeping only the part without substring. For example,
def rchop(string, ending): if string.endswith(ending): return string[:-len(ending)] return string chopped_str = rchop('Hello world', 'orld') print chopped_str
This will give the output:
Hello w
If speed is not important, you can also use a regex here. For example,
>>> import re >>> re.sub('orld$', '', 'Hello world') Hello w
- Related Questions & Answers
- How do I remove a string from an array in a MongoDB document?
- How do I remove a property from a JavaScript object?
- How can I remove the ANSI escape sequences from a string in python?
- Write a Python program to remove a certain length substring from a given string
- How do I create a Java string from the contents of a file?
- Java Program to remove whitespace from the beginning and end of a string
- How do I remove a uniqueness constraint from a MySQL table?
- C# Program to remove the end part of a string
- How to extract a substring from inside a string in Python?
- How do I remove the Y-axis from a Pylab-generated picture?
- How do I remove multiple elements from a list in Java?
- How can we get substring from a string in Python?
- How do I remove a MySQL database?
- How do I do a case insensitive string comparison in Python?
- How do I wrap a string in a file in Python?
Advertisements