Through this code, i wish to replace all the dots (.) appearing in the string s with the character present at exactly the symmetrically opposite position. For eg: if s=a.bcdcbba, then the . should be replaced by b
i.e:
The element at ith position should be replaced by the element at len(s)-i-1th position. This function gives wrong output for the cases like g.... , .g... etc. Any help ?
def replacedots(s):
for i in range(0,len(s)):
if s[i]==".":
s=s.replace(s[i],s[len(s)-i-1],1)
return s
Szabolcs Dombi
5,8014 gold badges43 silver badges73 bronze badges
1 Answer 1
@chepner's way:
def replacedots(s):
return ''.join(x if x !='.' else y for x, y in zip(s, reversed(s)))
an alternative:
def replacedots(s):
return ''.join(c if c != '.' else s[-i - 1] for i, c in enumerate(s))
When the char at position i and the char at position len(s) - i - 1 is a . the dot will remain a dot.
Example:
s = "foo.bar"
answered Sep 9, 2016 at 14:17
Szabolcs Dombi
5,8014 gold badges43 silver badges73 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
C.LECLERC
Nice ! but isn't
s[-i - 1] enought to get the opposite char ?Szabolcs Dombi
sure, thank you (next time feel free to edit an answer you can improve) :)
chepner
Some--me :)--might find it cleaner to use
x if x !='.' else y for x, y in zip(s, reversed(s)) and avoid direct indexing. Either way, it is faster to pass a list comprehension instead of a generator to ''.join. (Oddly enough, the zip version is faster than theenumerate version when generators are used, but not when both are used as list comprehensions.)lang-py
"foo.bar"?s.replacedoesn't replace the dot atibut the first dot.