newbie: modifying a string in python

Charles Hartman charles.hartman at conncoll.edu
Wed Mar 16 15:07:44 EST 2005


You're right that the code you give will not have the desired effect, 
because strings (unlike lists) are immutable. But slicing comes to your 
rescue:
	for s in stks:
		s = s.strip()
		if s[-2:] == 'GR':
			s = s[:-2] + 'GF'
-- though I'm sure more experienced people will offer more efficient 
solutions.

Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar
http://villex.blogspot.com

>  want to modify a string in the following way :
> for s in stks:
>       s = s.strip()
>       if ( s[-2:] == ‘GR’ ):
>               s[-2:]= ‘GF’
>  
> so, if the last two characters are GR, I want to change
> them to GF ( there will be other if statements also but I am
> just putting this one here for simplicity ).
>  
> I think the code is fine but I vaguely remember
> reading somewhere in the documentation that
> python strings can’t be changed ( only elements of lists can be ) ?.
> Is that true or is it okay to do the above.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 1103 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050316/c2235b63/attachment.bin>


More information about the Python-list mailing list