Python From Beginner to Advanced

0% completed

Previous
Next
Updating Strings in Python

In Python, strings are immutable, meaning their individual characters cannot be changed after creation. However, you can modify a string indirectly by creating a new string with the desired changes. This is done using techniques like slicing, concatenation, and string replacement.

Modifying Strings Using Slicing and Concatenation

Since strings cannot be modified in place, you can create a new string by slicing the original string and concatenating the updated part.

Example 1: Changing a Word in a String

Python3
Python3

. . . .

Explanation

  1. original_string[:7] extracts "Hello, " (characters from index 0 to 6).
  2. "Python!" is concatenated to form the new string "Hello, Python!".
  3. The original string remains unchanged, and a new string is created with modifications.

Modifying Strings Using "replace()" Method

The replace() method is another way to update strings by replacing specific parts with new values.

Example 2: Using "replace()" to Modify a String

Python3
Python3

. . . .

Explanation

  1. The replace() method finds "Java" in the string and replaces it with "Python".

  2. A new string is created, while the original string remains unchanged.

Since Python strings are immutable, modifying them requires creating new strings rather than changing the existing ones. You can achieve this using slicing and concatenation for structural changes or replace() for direct text replacement.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next