[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-list
Subject:    Re: string methods
From:       "Martin_v._Löwis" <martin () v ! loewis ! de>
Date:       2005-07-31 17:16:55
Message-ID: 42ed078a$0$6841$9b622d9e () news ! freenet ! de
[Download RAW message or body]

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
-- 
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic