【问题标题】:python3: removing several chars from a string with a long chain of .replace().replace().replace()python3:从具有长链.replace().replace().replace()的字符串中删除几个字符
【发布时间】:2011-02-26 21:00:02
【问题描述】:

我在堆栈溢出中找到了这个示例。我理解,但对于这样一个简单的方法概念来说似乎有点过分......从字符串中删除几个字符。

导入字符串 排除 = 设置(字符串。标点符号) s = ''.join(ch for ch in s if ch not in exclude)

python 3.1 中是否有一个内置的字符串方法来做一些事情:

s = "a,b,c,d,e,f,g,h,i" s = s.strip([",", "d", "h"])

代替:

s = s.replace(",", "").replace("d", "").replace("h", "")

【问题讨论】:

    标签: string methods python-3.x


    【解决方案1】:

    我不同意您找到的示例过于复杂。对于您的用例,该代码将变为:

    s = ''.join(ch for ch in s if ch not in ",dh")
    

    这对我来说似乎很简洁。但是,还有一种替代方法,它更简洁一些,并且可能更有效:

    s = s.translate(str.maketrans("", "", ",dh"))
    

    免责声明:我没有实际测试过这段代码,因为我无法访问 Python 3.1 解释器。 Python 2.6(我已经测试过)中的等价物是:

    t = ''.join(chr(i) for i in range(256))
    s = s.translate(t, ",dh")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多