Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using replace() method in python by index [duplicate]

Tags:

python

replace

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"?

like image 480
Oscar Johansson Avatar asked Aug 09 '16 21:08

Oscar Johansson


People also ask

How do you replace a word with an index in Python?

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.

How do you replace a string with an index in Python?

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.

What does replace () do in Python?

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.


2 Answers

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:]
like image 65
nbryans Avatar answered Oct 28 '22 05:10

nbryans


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.

like image 20
dsh Avatar answered Oct 28 '22 05:10

dsh