0

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    
9
  • 2
    what about "foo.bar"? Commented Sep 9, 2016 at 14:07
  • Do you mean the character after the dot? Commented Sep 9, 2016 at 14:08
  • It's because s.replace doesn't replace the dot at i but the first dot. Commented Sep 9, 2016 at 14:09
  • You need to add what you expect as output for the corner cases Commented Sep 9, 2016 at 14:27
  • 1
    Thanks every one ! Especially @Dombi Szabolcs . Commented Sep 10, 2016 at 3:01

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Nice ! but isn't s[-i - 1] enought to get the opposite char ?
sure, thank you (next time feel free to edit an answer you can improve) :)
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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.