string methods

"Martin v. Löwis" martin at
Sun Jul 31 19:16:55 CEST 2005

anthonyberet wrote:
> For example if I wanted to replace the 4th character in 'foobar' (the 
> b)with the contents of another string, newchar, what would be the 
> easiest way?

Depends on how your input is specified. If you know it is the b you
want to replace, you write

 >>> text="foobar"
 >>> text = text.replace("b","baz")
 >>> text

There is no issue with immutability here: .replace returns a new
string object, and you assign this to the text variable (thus dropping
the reference to the string "foobar").

If you know it is the fourth character you want to replace, you
do as people have suggested:

 >>> text="foobar"
 >>> text=text[:3]+"baz"+text[4:]
 >>> text

And, if you know in advance that the string is "foobar", and that
it is the fourth character, and that the replacement string is "baz",
you write

 >>> text="foobazar"



More information about the Python-list mailing list