Change first occurrence of character x in a string - how?

Chris Green cl at isbd.net
Sun Feb 14 16:54:07 EST 2021


MRAB <python at mrabarnett.plus.com> wrote:
> On 2021-02-14 21:14, Chris Green wrote:
> > What's the easiest way to change the first occurrence of a specified
> > character in a string?
> > 
> > E.g. I want to change linux-raid.vger.kernel.org to
> > linux-raid at vger.kernel.org, it's a fairly general requirement of
> > needing to change '.' to '@'.
> > 
> > Alternatively is there an RE 'match' function that would test if
> > linux-raid at vger.kernel.org matches linux-raid.vger.kernel.org? I don't
> > really care if the '.' are all regarded as wild cards, the match will
> > be accurate enough.
> > 
> Use the .replace method. Its 3rd argument is the maximum number of 
> replacements, in this case 1:
> 
> >>> s = 'linux-raid.vger.kernel.org'
> >>> s.replace('.', '@', 1)
> 'linux-raid at vger.kernel.org'

Yes, thank you, simple! :-)

-- 
Chris Green
·


More information about the Python-list mailing list