October 27th, 2012, 08:32 PM
Changing a character in a string
How would you change a character in a string.
from: string = "cat"
to: string = "cot"
October 27th, 2012, 08:52 PM
I'd convert the string to a list, make the changes, then convert back to a string.
>>> s = list('cat')
['c', 'a', 't']
>>> s = 'o'
[/code] are essential for python code and Makefiles!
October 27th, 2012, 11:13 PM
To elaborate on b's reply, you technically can't do what you posted, since strings in Python are immutable: they cannot be "changed." However, lists are mutable, so you can take a sting apart into a list, change the list, and put it back together into a different string. You can even use the old variable name (`string' in your example) to refer to the new string, so it's essentially as if you had changed the string. (But not completely: if there were other references to the original string in your program, they will still refer to the old string.)
Originally Posted by Dzung
October 29th, 2012, 11:45 PM
In your example, why is ''.join(s), even needed? Or I should say what is the purpose of adding it?
Originally Posted by b49P23TIvg
October 30th, 2012, 03:29 AM
['c', 'o', 't'] is a list. ''.join(['c', 'o', 't']) is a string. This is the third part of the procedure I stated in my post (putting the list back together into a string).
Originally Posted by spiralbrain
October 30th, 2012, 04:47 PM
Originally Posted by Lux Perpetua