[Tutor] Reformatting phone number

Kent Johnson kent37 at tds.net
Thu Aug 21 01:41:26 CEST 2008


On Wed, Aug 20, 2008 at 4:43 PM, Dotan Cohen <dotancohen at gmail.com> wrote:
> I have a small script (linux) that takes a phone number as an argument:
> #!/usr/bin/env python
> import sys
> number = '+' + sys.argv[1]
> ....
>
> However, if the first digit of the phone number is a 0 then I need to
> replace that 0 with "972". I can add the "972", but how do I remove
> the leading "0"?
>
> For instance, this code:
> #!/usr/bin/env python
> import sys
> if sys.argv[1][0] == 0:

Another way to write this is
  if sys.argv[1].startswith('0'):

>    number = '+972' + sys.argv[1]

You need to learn about slicing. This is a way of indexing any
sequence, including strings. See
http://docs.python.org/tut/node5.html#SECTION005120000000000000000
http://docs.python.org/lib/typesseq.html

In particular, you want
  number = '+972' + sys.argv[1][1:]

which takes all characters of argv[0] after the first.

Kent


More information about the Tutor mailing list