Shasti
Shasti

Reputation: 91

Python String replace behaves differently

The below string replace code prints "XXaXXbXXcXX1XX2XX3XX". I know there is a reason behind it but having hard time finding it. Can someone please explain why?

if __name__ == '__main__':
    match = ""
    replace = "XX"
    strr = "abc123"
    print strr.replace(match, replace)

Upvotes: 1

Views: 201

Answers (2)

Clodion
Clodion

Reputation: 1017

You replace every "" (empty string) by "XX". Python consider that between two character there is a empty string!!! And before the first character and after the last.
It's just that!

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599570

It's replacing the empty string between each pair of characters with XX.

Upvotes: 3

Related Questions