Editing strings by index maybe something that we don’t do all the time. But it’s one of these things that, coming from languages like C, one would assume is as trivial as assigning the value of an indexed position. Something like this:
-
var a = "hello world"
-
a[0] = "H"
-
console.log(a) // outputs "hello world"
Go ahead and paste that code in your favorite javascript console. You would expect the output to be “Hello there”, but it is not.
Same goes with Python, check this code:
-
>>> a = "hello world"
-
>>> a[0] = "H"
-
Traceback (most recent call last):
-
File "<stdin>", line 1, in <module>
-
TypeError: 'str' object does not support item assignment
-
>>> a[0] = 'H'
-
Traceback (most recent call last):
-
File "<stdin>", line 1, in <module>
-
TypeError: 'str' object does not support item assignment
This is because strings are read only and cannot be modified at all. Only replaced with new strings.
The solution: convert to array and back to string
There may be other solutions out there, I’m sure, but this is the solution I use: Both in Python and Javascript, a string can be converted into an array or list of characters (actually, list of strings). Then we can modify values by index and finally join the output into a new string.
Javascript:
-
var a = "hello world"
-
a = a.split("")
-
a[0] = "H"
-
a = a.join("")
-
console.log(a) // outputs "Hello world"
Python:
-
>>> a = "hello world"
-
>>> a = list(a)
-
>>> a[0] = "H"
-
>>> a = "".join(a)
-
>>> a
-
'Hello world'
It’s interesting to see how the syntax for joining arrays into strings is totally the opposite in Javascript and Python. In Javascript, join() is a function of the Array object while in Python join() is a function of the string class.
In the other hand, split() is a method of the String object in Javascript. There is a split() function on the string class in Python, but it cannot be used to split strings without a specific separator. The list() function/constructor does the trick.