Python string replace the values
Peter Otten
__peter__ at web.de
Sat Sep 2 03:05:35 EDT 2017
Steve D'Aprano wrote:
> On Sat, 2 Sep 2017 03:13 am, Ganesh Pal wrote:
>
>> Example :
>>
>> "a0000" and "1" => a0001
>>
>> "a0000" and "aa" => c00aa
>
> Why does the leading 'a' change to a 'c'? Is that a mistake? I'll assume
> its a typo.
>
> You want string slicing.
>
> base = 'a0000'
> extra = 'ab'
assert len(extra)
> print( base[:-len(extra)] + extra )
or
base[:-len(extra) or None] + extra
if you need to handle the extra = "" case.
Another option is a template:
>>> "a{:0>4}".format("")
'a0000'
>>> "a{:0>4}".format("xy")
'a00xy'
>>> "a{:0>4}".format("xyztu")
'axyztu'
This can be modified to limit its arg by specifying a precision:
>>> "a{:0>4.4}".format("xyztu")
'axyzt'
More information about the Python-list
mailing list