Added the way to modify immutable string. (#25334)
* Added the way to modify immutable string. * Formatting changes
This commit is contained in:
@ -20,7 +20,15 @@ Python allows `str` objects, or _strings_, to be expressed in a few different wa
|
|||||||
File "<stdin>", line 1, in <module>
|
File "<stdin>", line 1, in <module>
|
||||||
TypeError: 'str' object does not support item assignment
|
TypeError: 'str' object does not support item assignment
|
||||||
|
|
||||||
|
Instead, you can convert the string into a list, modify the list element (string character) you wish to change, and then join the list elements back to a string, like so:
|
||||||
|
|
||||||
|
>>> foo = "my string"
|
||||||
|
>>> foo_list_form = list(foo)
|
||||||
|
>>> foo_list_form[0] = "a"
|
||||||
|
>>> foo = ' '.join(foo_list_form)
|
||||||
|
>>> print(foo)
|
||||||
|
ay string # The required output
|
||||||
|
|
||||||
## Reference:
|
## Reference:
|
||||||
|
|
||||||
<a href='https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str' target='_blank' rel='nofollow'>Text Sequence Type _str_</a>
|
<a href='https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str' target='_blank' rel='nofollow'>Text Sequence Type _str_</a>
|
||||||
|
Reference in New Issue
Block a user