简体   繁体   English

在字符串中的每个字符前后放置一个符号

[英]Put a symbol before and after each character in a string

I would like to add brackets to each character in a string. 我想为字符串中的每个字符添加括号。 So 所以

"HelloWorld"

should become: 应成为:

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

I have used this code: 我用过这段代码:

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

which is the most straightforward way to do it but the string concatenations are pretty slow. 这是最简单的方法,但字符串连接非常慢。 Any suggestions on speeding up this code. 有关加快此代码的任何建议。

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

If string is huge then using str.join with a list comprehension will be faster and memory efficient than using a generator expression( https://stackoverflow.com/a/9061024/846892 ): 如果字符串很大,那么使用带有列表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]'

From Python performance tips : Python性能提示

Avoid this: 避免这个:

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

Use s = "".join(list) instead. 请改用s = "".join(list) The former is a very common and catastrophic mistake when building large strings. 在构建大型字符串时,前者是一个非常常见和灾难性的错误。

The most pythonic way would probably be with a generator comprehension: 最Python的方式可能是通过生成器理解:

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

Ashwini Chaudhary's answer is very similar, but uses the modern (Python3) string format function. Ashwini Chaudhary的答案非常相似,但使用了现代(Python3)字符串格式函数。 The old string interpolation with % still works fine and is a bit simpler. 使用%的旧字符串插值仍然可以正常工作,并且更简单。

A bit more creatively, inserting ][ between each character, and surrounding it all with [] . 更具创造力的是,在每个字符之间插入][ ,并用[]括起来。 I guess this might be a bit faster, since it doesn't do as many string interpolations, but speed shouldn't be an issue here. 这可能会快一些,因为它没有那么多的字符串插值,但速度不应该是一个问题。

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

If you are concerned about speed and need a fast implementation, try to determine an implementation which offloads the iteration to the underline native module. 如果您担心速度并需要快速实现,请尝试确定将迭代卸载到下划线本机模块的实现。 This is true for at least in CPython. 至少在CPython中这是事实。

Suggested Implementation 建议的实施

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

Output 产量

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

Comparing with a competing solution 与竞争解决方案相比

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM