Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: rstrip one exact string, respecting order

Is it possible to use the python command rstrip so that it does only remove one exact string and does not take all letters separately?

I was confused when this happened:

>>>"Boat.txt".rstrip(".txt") >>>'Boa' 

What I expected was:

>>>"Boat.txt".rstrip(".txt") >>>'Boat' 

Can I somehow use rstrip and respect the order, so that I get the second outcome?

like image 693
aldorado Avatar asked Sep 10 '13 15:09

aldorado


People also ask

What does Rstrip \n do in Python?

The rstrip() method returns a copy of a string with the trailing characters removed. The rstrip() method has one optional argument chars . The chars argument is a string that specifies a set of characters which the rstrip() method will remove from the copy of the str .

How do I remove a prefix from a string in Python?

There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .

What is Rstrip in Python example?

rstrip() The rstrip() method returns a copy of the string by removing the trailing characters specified as argument. If the characters argument is not provided, all trailing whitespaces are removed from the string.


2 Answers

You're using wrong method. Use str.replace instead:

>>> "Boat.txt".replace(".txt", "") 'Boat' 

NOTE: str.replace will replace anywhere in the string.

>>> "Boat.txt.txt".replace(".txt", "") 'Boat' 

To remove the last trailing .txt only, you can use regular expression:

>>> import re >>> re.sub(r"\.txt$", "", "Boat.txt.txt") 'Boat.txt' 

If you want filename without extension, os.path.splitext is more appropriate:

>>> os.path.splitext("Boat.txt") ('Boat', '.txt') 
like image 96
falsetru Avatar answered Sep 21 '22 14:09

falsetru


Starting with Python 3.9, use .removesuffix():

"Boat.txt".removesuffix(".txt") 

On earlier versions of Python, you'll have to either define it yourself:

def removesuffix(s, suf):     if suf and s.endswith(suf):         return s[:-len(suf)]     return s 

(you need to check that suf isn't empty, otherwise removing an empty suffix e.g. removesuffix("boat", "") will do return s[:0] and return "" instead of "boat")

or use regex:

import re suffix = ".txt" s = re.sub(re.escape(suffix) + '$', '', s) 
like image 27
nneonneo Avatar answered Sep 19 '22 14:09

nneonneo