insert chars into string

E

eight02645999

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
 
F

Felipe Almeida Lessa

Em Sex, 2006-03-17 às 17:32 -0800, (e-mail address removed) escreveu:
is there a string method to insert characters into a string?

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:]
 
D

Diez B. Roggisch

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..

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,455
Members
48,132
Latest member
KatlynC08

Latest Threads

Top