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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Strings are immutable. That means you can’t assign to them at all. You could use formatting:
Or concatenation:
Or replacement (thanks Odomontois for reminding me):
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.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:
And consider the
remodule 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.