By Lenin Mishra
If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.
Can we replace characters in a string in Python?
In Python, strings are immutable.
This means, elements of a string cannot be changed or replaced once they have been assigned.
x = "Pylenin" x = "L"
Traceback (most recent call last): File "file_location", line 2, in <module> x = "L" TypeError: 'str' object does not support item assignment
However, we can certainly create a copy of our string with our necessary replacements.
Method 1 - Python string replace() method
replace() method replaces a specified character/phrase with another.
Syntax of replace()
string.replace(oldstring, newstring, count) oldstring - The string to replace(required) newstring - The string to replace with(required) count - A number specifying how many occurrences of the old value you want to replace. Default is all occurrences (optional)
Replace all occurences of the word
txt = "I like Pylenin" x = txt.replace("Pylenin", "Python") print(x)
I like Python
Replace the first two occurrence of the word
txt = "Python is the best. " \ "I love Python. " \ "I enjoy Python" x = txt.replace("Python", "Pylenin", 2) print(x)
Pylenin is the best. I love Pylenin. I enjoy Python
Method 2 - Python list() method
Another solution would be to convert a string to a python list and then make necessary changes. Unlike Python strings, Python lists are mutable.
old_str = "foofoo" str_list = list(old_str) str_list = 'd' new_string = "".join(str_list) print(new_string)
- How to create a string in Python?
- How to access characters in a Python string?
- How to concatenate strings in Python?
- How to iterate through a string in Python?
- Check if a Substring is Present in a Given String
- Escape sequences in Python String
- Python String Formatting - The Definitive Guide
- Commonly used Python string methods