What is the best / correct way to use item assignment for python string ?
i.e s = "ABCDEFGH"
s[1] = 'a'
s[-1]='b'
?
Normal way will throw : 'str' object does not support item assignment
Strings in Python are immutable. This means that they cannot be changed. If you try to change the contents of an existing string, you're liable to find an error that says something like “'str' object does not support item assignment”.
The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string. Strings are immutable in Python, so we have to convert the string to a list, replace the list item and join the list elements into a string.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Strings are immutable. That means you can't assign to them at all. You could use formatting:
>>> s = 'abc{0}efg'.format('d') >>> s 'abcdefg'
Or concatenation:
>>> s = 'abc' + 'd' + 'efg' >>> s 'abcdefg'
Or replacement (thanks Odomontois for reminding me):
>>> s = 'abc0efg' >>> s.replace('0', 'd') 'abcdefg'
But keep in mind that all of these methods create copies of the string, rather than modifying it in-place. If you want in-place modification, you could use a bytearray
-- though that will only work for plain ascii strings, as alexis points out.
>>> b = bytearray('abc0efg') >>> b[3] = 'd' >>> b bytearray(b'abcdefg')
Or you could create a list of characters and manipulate that. This is probably the most efficient and correct way to do frequent, large-scale string manipulation:
>>> l = list('abc0efg') >>> l[3] = 'd' >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> ''.join(l) 'abcdefg'
And consider the re
module for more complex operations.
String formatting and list manipulation are the two methods that are most likely to be correct and efficient IMO -- string formatting when only a few insertions are required, and list manipulation when you need to frequently update your string.
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