sentence = 'this is a book.pdf'
sentence.replace( 'pdf' or 'PDF' ,'csv' )
sentence.replace('pdf','csv',re.IGNORECASE)
how can i replace the characters under the condition
- specified such as Pdf or PDF
- or Ignoring cases all together
sentence = 'this is a book.pdf'
sentence.replace( 'pdf' or 'PDF' ,'csv' )
sentence.replace('pdf','csv',re.IGNORECASE)
how can i replace the characters under the condition
I’m going to assume you are doing this to a string
sentence = sentence.lower()
Better yet just sentence.lower()
where you are using sentence next could do the trick hard to say without more context.
If you are doing this for multiple kinds of files then you can find the index of the period(.), delete everything after it and add the file extension to the end
sentence = sentence - sentence[sentence.index(".")+1:]
sentence += "csv"
Looks as if you want to truncate any file extension found and add .csv
. I would recommend using \w{1,5}
(one to five word chars) instead of \w+
(one or more), because of the case of files named an12n512n5125.1125n125n125
which I've had in my own file blobs often.
Match period followed by one or more alphanumeric characters at the end of string ($) and replace with .csv. Case sensitivity no longer matters:
import re
sentence = 'this is a book.pdf'
ext2 = 'csv'
sentence = re.sub(rf'\.\w+$', f'.{ext2}', sentence)
slice end of string, lowercase compare it to .pdf, and replace .pdf with .csv. Using string interpolation (f"") for customizable extensions
sentence = 'this is a book.pdf'
ext1 = 'pdf'
ext2 = 'csv'
sentence = sentence[:-4]+f'.{ext2}' if sentence[-4:].lower()==f'.{ext1}' else sentence
Using regex with $ to match end of string with re.IGNORECASE. Using string interpolation for customizable extensions
import re
sentence = 'this is a book.pdf'
ext1 = 'pdf'
ext2 = 'csv'
sentence = re.sub(rf'\.{ext1}$', f'.{ext2}', sentence, flags=re.IGNORECASE)