1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

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

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    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 tried a straightforward loop:

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


    But can I do it more efficiently? I'm concerned about the repeated string concatenations.


    See also: How to insert a character after every 2 characters in a string — note that techniques based on .join will not add anything before the first (or after the last) character, unless explicitly separately added.

    Continue reading...

Compartilhe esta Página