【问题标题】:Put a symbol before and after each character in a string在字符串中的每个字符之前和之后放置一个符号
【发布时间】:2014-02-04 14:08:19
【问题描述】:

我想为字符串中的每个字符添加括号。所以

"HelloWorld"

应该变成:

"[H][e][l][l][o][W][o][r][l][d]"

我用过这段代码:

word = "HelloWorld"
newWord = ""
for letter in word:
    newWord += "[%s]" % letter

这是最直接的方法,但字符串连接非常慢。 有关加快此代码的任何建议。

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:
    >>> s = "HelloWorld"
    >>> ''.join('[{}]'.format(x) for x in s)
    '[H][e][l][l][o][W][o][r][l][d]'
    

    如果字符串很大,那么将str.join 与列表推导一起使用将比使用生成器表达式(https://stackoverflow.com/a/9061024/846892) 更快且内存效率更高:

    >>> ''.join(['[{}]'.format(x) for x in s])
    '[H][e][l][l][o][W][o][r][l][d]'
    

    来自Python performance tips

    避免这种情况:

    s = ""
    for substring in list:
        s += substring
    

    请改用s = "".join(list)。前者在构建大字符串时是一个非常常见和灾难性的错误。

    【讨论】:

    • 如何检查这是否比其他代码快?
    • timeit,但这几乎可以肯定是因为你创建了 n 个新的字符串对象。
    • @MehdiNellen 阅读此wiki.python.org/moin/PythonSpeed/…,并使用timeit 模块。
    • @AshwiniChaudhary:如果速度是一个问题,将迭代卸载到下划线的本机代码可能至少在 CPython 中会带来一些性能优势。
    【解决方案2】:

    最pythonic的方式可能是使用生成器理解:

    >>> s = "HelloWorld"
    >>> "".join("[%s]" % c for c in s)
    '[H][e][l][l][o][W][o][r][l][d]'
    

    Ashwini Chaudhary 的答案非常相似,但使用了现代 (Python3) 字符串格式函数。使用 % 的旧字符串插值仍然可以正常工作,并且更简单一些。

    更有创意,在每个字符之间插入][,并用[] 包围它。我这可能会快一点,因为它不会做那么多的字符串插值,但速度在这里应该不是问题。

    >>> "[" + "][".join(s) + "]"
    '[H][e][l][l][o][W][o][r][l][d]'
    

    【讨论】:

    • 看起来不错,我用过这段代码,虽然没有检查它是否是最快的。 :)
    • @MehdiNellen:在不了解您的代码的情况下,我猜速度上的差异应该无关紧要。选择最干净的版本,或者您最了解的版本。如果结果是瓶颈,您仍然可以在之后进行优化。
    • >>> timeit.timeit("''.join('[%s]' % c for c in 'lol')", number=100000) 0.36499309539794922 >>> timeit.timeit( '"[" + "][".join("lol") + "]"', number=100000) 0.1732938289642334
    • 你的第二个选项是我想到的第一个选项,除了我会使用格式:"[{}]".format(']['.join(s))
    • FWIW,如果你想节省几微秒,python timeit.py 在我的系统上说"".join("[%s]" % c for c in s) 是 4.7μs,"["+"][".join(s)+"]" 是 1.41μs 每个循环(我的替代使用格式是 1.8μs )。 YMMV
    【解决方案3】:

    如果您关心速度并需要快速实现,请尝试确定将迭代卸载到下划线原生模块的实现。至少在 CPython 中是这样。

    建议实施

    "[{}]".format(']['.join(s))
    

    输出

    '[H][e][l][l][o][W][o][r][l][d]'
    

    与竞争解决方案比较

    In [12]: s = "a" * 10000
    
    In [13]: %timeit "[{}]".format(']['.join(s))
    1000 loops, best of 3: 215 us per loop
    
    In [14]: %timeit ''.join(['[{}]'.format(x) for x in s])
    100 loops, best of 3: 3.06 ms per loop
    
    In [15]: %timeit ''.join('[{}]'.format(x) for x in s)
    100 loops, best of 3: 3.26 ms per loop
    

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多