【问题标题】:What is the best way to do this replace a list of characters with '-' in a string.?执行此操作的最佳方法是用字符串中的“-”替换字符列表。?
【发布时间】:2019-07-16 19:01:55
【问题描述】:

我想用“-”替换这些符号,我知道应该有比这样做更好的方法:

if '/' in var1:
    var1= var1.replace('/', '-')
if '#' in var1:
    var1= var1.replace('#', '-')
if ';' in var1:
    var1 = var1.replace(';', '-')
if ':' in var1:
    var1= var1.replace(':', '-')

这是我尝试过的,这显然是错误的,我无法正确优化它。

str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
a = ['#',':',';','/']
print([str.replace(i,'-') for i in str])

replaceAll 不起作用,给我一个错误,说 str 没有该属性。

str.replaceAll("[<>]", "")

【问题讨论】:

    标签: python-3.x list list-comprehension


    【解决方案1】:

    str.translate()怎么样?

    # make a translation table that replaces any of "#:;/" with hyphens
    hyphenator = str.maketrans({c: "-" for c in "#:;/"})
    # use str.translate to apply it
    print("Testing PRI/Sec (#434242332;PP:432:133423846,335)".translate(hyphenator))
    

    或者,甚至更快,使用已编译的正则表达式:

    compiled_re = re.compile("|".join(re.escape(i) for i in "#:;/"))
    print(compiled_re.sub("-", "Testing PRI/Sec (#434242332;PP:432:133423846,335)"))
    

    这两种方法都比提出的其他方法快得多(至少在那个输入上):

    import re
    import timeit
    
    s = "Testing PRI/Sec (#434242332;PP:432:133423846,335)"
    a = ["#", ":", ";", "/"]
    hyphenator = str.maketrans({c: "-" for c in "#:;/"})
    
    
    def str_translate():
        s.translate(hyphenator)
    
    
    def join_generator():
        "".join("-" if ch in a else ch for ch in s)
    
    
    def append_in_loop():
        temp = ""
        for i in s:
            if i in a:
                temp += "-"
            else:
                temp += i
    
    
    def re_sub():
        re.sub("|".join(re.escape(i) for i in a), "-", s)
    
    def compiled_re_sub():
        compiled_re.sub("-", s)
    
    for method in [str_translate, join_generator, re_sub, append_in_loop, compiled_re_sub]:
        # run a million iterations and report the total time
        print("{} took a total of {}s".format(method.__name__, timeit.timeit(method)))
    

    我的机器上的结果:

    str_translate took a total of 1.1160085709998384s
    join_generator took a total of 4.599312704987824s
    re_sub took a total of 4.101858579088002s
    append_in_loop took a total of 4.257988628000021s
    compiled_re_sub took a total of 1.0353244650177658s
    

    【讨论】:

    • 如果你re.compilere_sub()函数外先是正则表达式,这个正则表达式是最快的。
    【解决方案2】:
    s = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
    a = ['#',':',';','/']
    
    print(''.join('-' if ch in a else ch for ch in s))
    

    打印:

    Testing PRI-Sec (-434242332-PP-432-133423846,335)
    

    或者使用re:

    s = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
    a = ['#',':',';','/']
    
    import re
    print(re.sub('|'.join(re.escape(i) for i in a), '-', s))
    

    打印:

    Testing PRI-Sec (-434242332-PP-432-133423846,335)
    

    【讨论】:

      【解决方案3】:

      使用重新打包

      import re
      string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
      result = re.sub('[#:;/]',"-", string)
      print(result)
      

      结果:

      Testing PRI-Sec (-434242332-PP-432-133423846,335)
      

      【讨论】:

        【解决方案4】:

        只需循环将每个字符添加到临时变量中,除非它在列表中“a”如果它在列表中,只需通过在变量中添加“-”来替换它。

        str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
        a = ['#',':',';','/']
        temp = ''
        for i in str:
            if i in a:
                temp = temp + "-"
            else:
                temp = temp + i
        print(temp)
        

        【讨论】:

          猜你喜欢
          • 2011-10-16
          • 1970-01-01
          • 2011-03-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-09
          相关资源
          最近更新 更多