π Day 68/150 – Replace Characters in String in Python
Sometimes we need to replace characters or words inside a string.
Example:
"Python" → Replace "P" with "J" → "Jython"
Python makes this super simple using different methods π
πΉ Method 1 – Using replace()
text = "Python"
Jythonresult = text.replace("P", "J") print(result)
✅ Output
π replace() replaces all matching characters or words in a string.
πΉ Method 2 – Taking User Input
text = input("Enter a string: ") old_char = input("Enter character to replace: ") new_char = input("Enter new character: ") result = text.replace(old_char, new_char) print("Updated String:", result)
✅ Example Output
Enter a string: banana
Enter character to replace: a
Enter new character: o
Updated String: bonono
π Useful when replacement values come from the user.
πΉ Method 3 – Using for Loop
abbletext = "apple" result = "" for ch in text: if ch == "p": result += "b" else: result += ch print(result)
✅ Output
π This method manually checks every character and replaces matching ones.
πΉ Method 4 – Using List Comprehension
he**otext = "hello" result = "".join(["*" if ch == "l" else ch for ch in text]) print(result)
✅ Output
π A compact and Pythonic way to replace characters.
π₯ Key Takeaways
✅ replace() is the simplest method
✅ Loops help understand string manipulation logic
✅ List comprehension makes code shorter and cleaner
✅ String replacement is useful in text processing and cleaning
✅ Strings are immutable, so replacement creates a new string


0 Comments:
Post a Comment