Updating Strings in Python

You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.

String Reassignment

Since strings are immutable in Python, you cannot modify them directly. Instead, you create a new string ?

var1 = 'Hello World!'
var1 = 'Hello Python!'
print("Updated String:", var1)
Updated String: Hello Python!

Combining Parts of Original String

You can create a new string by combining parts of the original string with new content ?

var1 = 'Hello World!'
updated_string = var1[:6] + 'Python'
print("Updated String:", updated_string)
Updated String: Hello Python

Using String Methods

String methods like replace() return a new string with modifications ?

var1 = 'Hello World!'
updated_string = var1.replace('World', 'Python')
print("Updated String:", updated_string)
print("Original String:", var1)  # Original remains unchanged
Updated String: Hello Python!
Original String: Hello World!

Using Format Strings

F-strings provide a modern way to create updated strings with dynamic content ?

name = "World"
greeting = f"Hello {name}!"
print("Original:", greeting)

name = "Python"
updated_greeting = f"Hello {name}!"
print("Updated:", updated_greeting)
Original: Hello World!
Updated: Hello Python!

Conclusion

Python strings are immutable, so "updating" means creating new strings. Use slicing, string methods, or f-strings to generate modified versions while preserving the original string.

Updated on: 2026-03-25T07:32:16+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements