insert chars into string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • eight02645999@yahoo.com

    insert chars into string

    hi
    is there a string method to insert characters into a string?
    eg
    str = "abcdef"
    i want to insert "#" into str so that it appears "abc#def"

    currently what i did is convert it to a list, insert the character
    using insert() and then join them back as string..
    thanks

  • Felipe Almeida Lessa

    #2
    Re: insert chars into string

    Em Sex, 2006-03-17 às 17:32 -0800, eight02645999@y ahoo.com escreveu:[color=blue]
    > is there a string method to insert characters into a string?[/color]

    As far as I know, no. Strings are immutable in Python. That said, the
    following method may do what you want:

    def insert(original , new, pos):
    '''Inserts new inside original at pos.'''
    return original[:pos] + new + original[pos:]

    Comment

    • Diez B. Roggisch

      #3
      Re: insert chars into string

      eight02645999@y ahoo.com schrieb:[color=blue]
      > hi
      > is there a string method to insert characters into a string?
      > eg
      > str = "abcdef"
      > i want to insert "#" into str so that it appears "abc#def"
      >
      > currently what i did is convert it to a list, insert the character
      > using insert() and then join them back as string..[/color]

      If you are frequently want to modify a string in such a way, that this
      is the recommended way to do so. It might be that there are
      mutable-string implementations out there that make that easier for you -
      but in the end, it boils down to using list, so that the overhead of
      concatenating strings is encountered only once, on the end when you
      actually need the result.

      Diez

      Comment

      Working...