I want to do something like this.
example_string = "test"
print(example_string.replace(example_string[0], "b"))
expecting the output
best
however because the letter "t" is being passed into the method the t at the end also gets replaced with a "b". Resulting in the output
besb
How do I do it in a way that would result in the output "best" instead of "besb"?
You can replace multiple characters in the given string with the new character using the string indexes. For this approach, you can make use of for loop to iterate through a string and find the given indexes. Later, the slicing method is used to replace the old character with the new character and get the final output.
As strings are immutable in Python, just create a new string which includes the value at the desired index. You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
The problem is that .replace(old, new)
returns a copy of the string in which the occurrences of old
have been replaced with new
.
Instead, you can swap the character at index i
using:
new_str = old_str[:i] + "b" + old_str[i+1:]
Check the documentation.
You can use
example_string.replace(example_string[0], "b", 1)
though it would be much more natural to use a slice to replace just the first character, as @nbryans indicated in a comment.
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