What is the easiest way in Python to replace a character in a string?
For example:
text = "abcdefg"; text[1] = "Z"; ^
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
There are three ways. For the speed seekers I recommend 'Method 2'
Method 1
Given by this answer
text = 'abcdefg' new = list(text) new[6] = 'W' ''.join(new)
Which is pretty slow compared to 'Method 2'
timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000) 1.0411581993103027
Method 2 (FAST METHOD)
Given by this answer
text = 'abcdefg' text = text[:1] + 'Z' + text[2:]
Which is much faster:
timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000) 0.34651994705200195
Method 3:
Byte array:
timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000) 1.0387420654296875
Don't modify strings.
Work with them as lists; turn them into strings only when needed.
>>> s = list("Hello zorld") >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] >>> s[6] = 'W' >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> "".join(s) 'Hello World'
Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With