Bobys Bobys - 1 month ago 10
Python Question

Python remove first number from string if it's 0

I'm getting a string from a form format

07123456789
(it's a phone number) and I would like to remove the first number/character only if it's a zero. And after that add
44
in front. So the output will be
447123456789
.

Which is the best way to do it?

Answer

Use str.startswith

In [11]: s = '07123456789'

In [12]: '44{}'.format(s[1:] if s.startswith('0') else s)
Out[12]: '447123456789'

Also, instead of formatting, you can join the strings together with + operator:

'44' + (s[1:] if s.startswith('0') else s)

If you're sure there's at most 1 zero at the beginning of the number, you can safely use str.lstrip or int conversion (see other answers).