python使用替换相同名称来减少代码

时间:2017-05-04 12:16:05

标签: python string replace

是否有可能减少此代码?

    Nomefilm = selected_channel[1]
    Nomefilm = Nomefilm.replace('.','').replace('-','').replace('(','').replace(')','').replace('[HD]','').replace('2013','').replace('2014','').replace('2015','').replace('2016','')
    Nomefilm = Nomefilm.replace('PrimaVisione 1','').replace('PrimaVisione 2','').replace('PrimaVisione 3','').replace('PrimaVisione 4','').replace('PrimaVisione 5','').replace('PrimaVisione 6','').replace('PrimaVisione 7','')
    Nomefilm = Nomefilm.replace('PrimaVisione 8','').replace('PrimaVisione 9','').replace('PrimaVisione 10','').replace('PrimaVisione 11','').replace('PrimaVisione 12','').replace('PrimaVisione 13','').replace('PrimaVisione 14','')
    Nomefilm = Nomefilm.replace('PrimaVisione 15','').replace('PrimaVisione 16','').replace('PrimaVisione 17','').replace('PrimaVisione 18','').replace('PrimaVisione 19','').replace('PrimaVisione 20','').replace('PrimaVisione 21','')
    Nomefilm = Nomefilm.replace('Primafila 1-2','').replace('Primafila 3-4','').replace('Primafila 5-6','').replace('Primafila 7-8','').replace('Primafila 9-10','').replace('Primafila 11-12','').replace('Primafila 13-14','').replace('Primafila 15','')
    Nomefilm = Nomefilm.replace('Primafila 16-17','').replace('Primafila 18','').replace('Primafila 19','')

1 个答案:

答案 0 :(得分:2)

编写一个函数来删除任何目标字符串列表。

def erase( s, target):
    for t in target:
        s = s.replace( t, '')
    return s

然后

TO_ERASE = ( '.', '-', ',' , '(', ')', '[HD]', '2013', 
    ... 
    'Primafila 19',
)


Nomefilm = erase( Nomefilm, TO_ERASE)

您也可以使用正则表达式(Python re模块)。例如,您可以删除所有以"Primafila "开头并以数字和连字符数量结尾的字符串

s = re.sub( 'Primafila\ [0-9\-]+', '', s)

请注意,这与您的代码不完全相同:它会很乐意将"Primafila 2345-------g"转换为"g"。它可能还需要您学习正则表达式的语法,正则表达式实际上是一种不同的语言(一种比Python更神秘的语言)。但是,如果类似字符串的数量太大而无法合理地作为列表提供,那么将其作为单个表达式处理可能是更好的方法。

正则表达式可以非常强大。一个正则表达式匹配"Primofila "后跟一位或两位数字,然后可选地用一个连字符和另一个一位或两位数字匹配'Primofila\ [0-9]{1,2}(-[0-9]{1,2})?'