In python, are strings mutable? The line someString[3] = "a"
throws the error
TypeError: 'str' object does not support item assignment
I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?
Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.
replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:]
or some other suitable approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With