Tuesday, July 26, 2022

Are strings mutable?

Strings are immutable which means that once the string is assigned to a specific variable the individual characters of that string cannot be changed. If we try to change the characters of the string the Python would raise the TypeError stating the 'str' i.e. string object does not support item assignment.
Example 1 Create a string "I want to change a character in a string." and then change the character at index 5.
Solution: First step is to create a string and assign it to a variable String.
String = "I want to change a character in a string."
The character at index 5 is the letter "t". To change the character at index 5 let's try the following code.
String[5] = "z"
Output:
TypeError: 'str' object does not support item assignment
The Python returned a Type Error since string are immutable. This means that once a string is defined it cannot be changed. However, there is an alternative to that problem and it is shown in Example 2. Example 2 Using a string from Example 1 create a new string with changed character at index 5 to "z".
Solution: The code for creating a string "I want to change a character in a string." is explained in Example 1
String = "I want to change a character in a string."
To change the letter at index 5 we will have to slice the initial variable String into two strings. The String1 will be a sliced string from 0 to 5 (not including 5) and the String2 variable will be the original String from 6 to the end of the String.
String1 = String[0:5]
String2 = String[6:]
To create a new string we will concatenate String1, "z", and "String2" together.
newString = String1 + "z" + String2
print("newString = {}".format(newString))
Output:>
newString = I wanz to change a character in a string."
The result showed that you can change specific characters in a string however you have to create string slices of the original string and then concatenate them togheter with new characters. The original string remained unchanged.

No comments:

Post a Comment