string methods

"Martin v. Löwis" martin at v.loewis.de
Sun Jul 31 13:16:55 EDT 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
'foobazar'

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
'foobazar'

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"

:-)

Regards,
Martin



More information about the Python-list mailing list