Bobys Bobys - 6 months ago 44
Python Question

Python remove first number from string if it's 0

I'm getting a string from a form format

(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
in front. So the output will be

Which is the best way to do it?


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).