Put a symbol before and after each character in a string

python, python-2.7, string

Solution

>>> 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):

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

From Python performance tips:

Avoid this:

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

Use `s = "".join(list)` instead. The former is a very common and catastrophic mistake when building large strings.

Problem

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.

Original source

Related problems