python - Overcoming the "disadvantages" of string immutability -


I want to change the value of a particular string index, but unfortunately

  string [ 4] = "A" picks a  TypeError , because the wire is irreversible ("item assignment is not supported"). 

So instead I used the waste instead

  string = string [: 4] + "a" + string [4:]  

Is there any better way to do this?

The strings in Python are irreversible, such as numbers and tuples, that means you can create them, Can move around, but can not change them. Why is it like this ? For some reasons (you can find a better discussion online):

  • From the design, the string in Python is considered to be original and irreversible. It uses better, safe programming styles.
  • There are efficiency gains in the reliability of the strings, mainly in the field of the following storage requirements.
  • It also saves the wire to use as a word key

If you see a little dragon around the web, you will see that "my How to change the string "is the most frequent advice for" Design your code so that you do not have to do this change ". Sufficient enough, but what are the other options? Here are some:

  • name = name [: 2] + 'g' + name [3:] - this is a incompetent way to do the job. Slice Semantics of Python ensure that it works correctly in all cases (as long as your index is in the limit), but with many string copies and combinations, this is your best shot on efficient code . Although you do not care about that (more opportunities), this is a solid solution.
  • Use the MutableString class module from UserString, though it is not more efficient than the previous method (it performs the same tricks under the hood), it is more consistent with normal string usage.
  • Use a list instead of string to store volatile data. Use the list to change back and forth and join, depending on what you actually need, ord and chr can also be useful.
  • Use an array object This is probably your best choice if you want to use the string to hold blocked data such as 'binary' bytes, and want fast code.

Pythyrized on Python Insights :-)


Comments