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)
# *****
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)
# *****
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:]
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)
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)
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****'