在re.IGNORECASE条件下,如何替换字符串中的字符

时间:2020-07-09 02:56:01

标签: python re python-textprocessing

sentence = 'this is a book.pdf'

sentence.replace( 'pdf' or 'PDF' ,'csv' )

sentence.replace('pdf','csv',re.IGNORECASE)

在这种情况下如何替换字符

  • 指定为Pdf或PDF
  • 或一起忽略个案

3 个答案:

答案 0 :(得分:0)

我将假设您正在对字符串执行

sentence = sentence.lower()

更好的是sentence.lower(),而在没有更多上下文的情况下,您很难在下一句中使用句子。

答案 1 :(得分:0)

如果要对多种文件执行此操作,则可以找到period(。)的索引,删除其后的所有内容,然后将文件扩展名添加到末尾

sentence = sentence - sentence[sentence.index(".")+1:]
sentence += "csv"

答案 2 :(得分:0)

似乎要截断找到的任何文件扩展名并添加.csv。我建议使用\w{1,5}(一到五个单词字符)而不是\w+(一个或多个字符),因为在我自己的文件中有一个名为an12n512n5125.1125n125n125的文件经常出现斑点。

匹配期,在字符串($)的末尾跟随一个或多个字母数字字符,并替换为.csv。区分大小写不再重要:

import re
sentence = 'this is a book.pdf'
ext2 = 'csv'
sentence = re.sub(rf'\.\w+$', f'.{ext2}', sentence)

字符串的结尾部分,将小写字母与.pdf进行比较,然后将.pdf替换为.csv。使用字符串插值(f“”)进行自定义扩展

sentence = 'this is a book.pdf'
ext1 = 'pdf'
ext2 = 'csv'
sentence = sentence[:-4]+f'.{ext2}' if sentence[-4:].lower()==f'.{ext1}' else sentence

使用带有$的正则表达式将字符串末尾与re.IGNORECASE匹配。将字符串插值用于可自定义的扩展名

import re
sentence = 'this is a book.pdf'
ext1 = 'pdf'
ext2 = 'csv'
sentence = re.sub(rf'\.{ext1}$', f'.{ext2}', sentence, flags=re.IGNORECASE)
相关问题