Reputation: 677
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?
Upvotes: 3
Views: 18378
Reputation: 19733
str.lstrip
is best for this case:
>>> s = '07123456789'
>>> '44'+s.lstrip('0')
'447123456789'
>>> s = '7123456789'
>>> '44'+s.lstrip('0')
'447123456789'
Upvotes: 3
Reputation: 10213
We can convert string into integer e.g.
>>> s = "07123456789"
>>> "44%s"%(int(s))
'447123456789'
We can use lstrip method of string which will remove all "0" from left of string. e.g.
>>> "44%s"%(s.lstrip("0"))
'447123456789'
If we want to consider only the first character from string then we can try following: (above two solution will not when more then one "0" at starting of string.)
>>> if s[0]=="0":
... s = s[1:]
...
>>> "44%s"%s
'447123456789'
Or go with solution from jamylak
>>> s = '07123456789'
>>> "44%s%s"%(s[0].strip("0"), s[1:])
'447123456789'
Upvotes: 5
Reputation: 46523
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 format
ting, 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).
Upvotes: 13
Reputation: 133504
Just another possible option:
>>> s = '07123456789'
>>> '44' + s[0].strip('0') + s[1:]
'447123456789'
Upvotes: 4
Reputation: 311053
One way to go about this is to cast to int
to remove the zero at the beginning and then cast back to a str
:
s = '07123456789'
s = '44'+str(int(s))
Upvotes: 1