single
Is String Mutable?
Swipe to show menu
You may recall something about mutable and immutable data types. Immutable cannot be changed .
But what about strings? They are immutable. You cannot change a string directly. Let's look at an example to see what happens. We will not have knowledge of the outcome unless we make an attempt. Therefore, let us examine this example.
123string = "What does it really take to be first past the post?" string[0] = 'k'
TypeError
Modifying string content is a common need. Python provides the replace() method to create a new string with the desired changes.undergo similar changes.
The replace() method was implemented to solve this problem. It has the following syntax:
string.replace(old_word, new_word)
Each string method creates a new string — the original is unchanged. In this example, replace() changes "seafood" to "fish":
12345678string = "I would like to order seafood" # I changed my mind and want to order fish now new_string = string.replace('seafood','fish') # The previous order print(string) # The current order print(new_string)
Swipe to start coding
As I said before, practice is the key to success; hence, here is another occasion to do it!
Correct the mistakes in the sentences string1, string2, and string3 to make them truthful. You should receive the following results:
"Paris is the capital of France"."Brasilia is located in South America"."Monkeys eat bananas".
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat