469,927 Members | 1,867 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,927 developers. It's quick & easy.

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

Mar 18 '06 #1
2 46004
Em Sex, 2006-03-17 *s 17:32 -0800, ei***********@yahoo.com 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:]

Mar 18 '06 #2
ei***********@yahoo.com schrieb:
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

Mar 18 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Ken Robinson | last post: by
10 posts views Thread by Ricardo | last post: by
7 posts views Thread by S Wheeler | last post: by
5 posts views Thread by vunet.us | last post: by
7 posts views Thread by HansWernerMarschke | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.