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
-- http://mail.python.org/mailman/listinfo/python-list