Change first occurrence of character x in a string - how?
Chris Green
cl at isbd.net
Sun Feb 14 16:51:42 EST 2021
Gary Herron <gherron at digipen.edu> wrote:
>
> On 2/14/21 1:14 PM, cl at isbd.net 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.
> >
> The string type has a replace function that does what you want.
> Except you can't change a string -- they are immutable -- so this
> creates a new string.
>
>
> >>> s = 'linux-raid.vger.kernel.org'
> >>> new_s = s.replace('.', '@', 1)
> >>> new_s
> 'linux-raid at vger.kernel.org'
>
A new string is fine, thank you, that'll do what I need. Efficiency
isn't a major issue with this.
--
Chris Green
ยท
More information about the Python-list
mailing list