0

I'm a newbie in Python and from yesterday, I got stuck to a problem. I tried to reduce it to a few lines, basically, the string is not updating.

e = '*****'
for i in e:
    if e.index(i) == 2:
        e = e.replace(i, 'P')
print(e)
# *****
Georgy
  • 12,464
  • 7
  • 65
  • 73
Gabriel
  • 43
  • 9
  • 2
    `e.index(i)` will never equal 2 here. It will always find the first `*` – Mark Apr 15 '20 at 18:20
  • 2
    first use `print()` to see what you get in variables inside `for` and `if`- and maybe you will see why it doesn't work. – furas Apr 15 '20 at 18:21
  • BTW: `index(i)` finds first element but you can use `index(i, start_position)` to search next elements. – furas Apr 15 '20 at 18:23
  • 1
    What is the issue, exactly? Have you done any debugging? I recommend reading https://ericlippert.com/2014/03/05/how-to-debug-small-programs/. – AMC Apr 15 '20 at 19:23
  • 1
    Does this answer your question? [Changing one character in a string in Python](https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python) – Georgy Apr 18 '20 at 15:08

4 Answers4

6

index(i) here is always equal to zero, since the index function finds the index of the first occurence ,ie, here its zero. So index is never 2 and the string is the same.
So to do that, lets use the join function:

''.join(e[i] if i!=2 else 'P' for i in range(len(e)))

gives:

'**P**'

Or as @furas says, slice:

e[:2] + 'P' + e[3:]
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
3

The problem with your code is that e.index(i) will return the first instance of that character type found, in this case, your entire string is '\*' characters, so e.index('\*') will always return 0: And your if statement never evaluates to True.

I would suggest the following code to accomplish the desired task:

e = '*****'
for index, character in enumerate(e):
    if index == 2:
        e = e[:index] + 'P' + e[index+1:]
print(e)
csymvoul
  • 677
  • 3
  • 15
  • 30
2

To keep your code in its similar format and still solve the problem you can do this:

e = "*****"
new_str = ""
for i, j in enumerate(e):
    if i == 2:
        j = "P"
    new_str += j
print(new_str)

This will also do it:

e = "*****"
e = e[:2] + "P" + e[3:]
print(e)
Joshua Hall
  • 332
  • 4
  • 15
1

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

https://docs.python.org/3/library/stdtypes.html#str.replace

So, replace() does not take an index. It finds a substring and replaces it with another one. To replace the character at index 1 with character 'X' you could do:

e = '*****'
e = e[:1] + 'X' + e[2:]  # '*X****'
Tomasito665
  • 1,188
  • 1
  • 12
  • 24