newbie : modifying a string in python

Brian van den Broek bvande at po-box.mcgill.ca
Wed Mar 16 15:16:32 EST 2005


Leeds, Mark said unto the world upon 2005-03-16 14:46:
> I 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.
> 
> .
> 
>                                    thanks

Hi Mark,

well, what happens when you try?

 >>> test_string = 'some text ending in GR'
 >>> if test_string[-2:] == 'GR':
... 	test_string[-2:] = 'GF'
...
Traceback (most recent call last):
   File "<interactive input>", line 2, in ?
TypeError: object doesn't support slice assignment


So, not so much :-)

You can do it thusly:

 >>> if test_string[-2:] == 'GR':
... 	test_string = test_string[:-2] + 'GF'
...
 >>> test_string
'some text ending in GF'

But, a better way in that it uses .endswith and points towards 
generalization:

 >>> old_chars = 'GR'
 >>> new_chars = 'GF'
 >>> test_string = 'some text ending in GR'
 >>> if test_string.endswith(old_chars):
... 	test_string = test_string[:-len(old_chars)] + new_chars
...
 >>> test_string
'some text ending in GF'
 >>>

Wrap that in a function:

def replace_at_end(string, old, new):
     # logic here with a return of the new string as the last line

and you've got something reusable :-)

(There may be better ways, still; I'm no expert :-)

HTH,

Brian vdB




More information about the Python-list mailing list