-1

I have to implement a function in python which returns a string of 4 characters from integers of 0 to 9999. The value of the string should begin with 0.

Example :

input:

3
22
123
1235

output:

0003
0022
0123
0123

The code that I have implemented is:

def stringtoZ(n):
    a = str(n)
    if(n < 10):
        string = "0" + "00" + a
    elif (n < 100):
        string = "0" + "0" + a
    elif (n < 1000):
        string = "0" + a
    else:
        string = "0" + a[:3]
    return string;

Normally the result is correct, but as I am a beginner in python, I wanted to know if there is another way which can be easier to implement this? Thank you so much!

Mohd
  • 5,523
  • 7
  • 19
  • 30
  • 1
    Use str(n).zfill(4). See https://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros – jarmod Nov 13 '19 at 23:29
  • @jarmod `zfill()` wouldn't work when the number has to start with 0 (and truncated if needed) – Mohd Nov 13 '19 at 23:36
  • @Mohd I'm not sure what you mean. Can you give me an example of an integer between 0 and 9999 that would be problematic? – jarmod Nov 13 '19 at 23:41
  • @jarmod OP's 4th example: `1235` -> `0123` – Mohd Nov 13 '19 at 23:42
  • @Mohd OK thanks, I didn't read that final example. What a strange requirement. OK, something like: `str(n).zfill(4) if n < 1000 else str(n//10).zfill(4)` – jarmod Nov 13 '19 at 23:47
  • @jarmod Yes, I'm not sure how `zfill()` is implemented but I think it would be faster than concatenating/slicing. I'll add it to my answer – Mohd Nov 13 '19 at 23:53

2 Answers2

1

You can use 4-len(a) if the number is less than 1000 to determine the number of leading zeroes and otherwise '0' + a[:3] to slice the first three numbers of the string. For example:

def stringtoZ(n):
    a = str(n)
    return '0' * (4-len(a)) + a if n < 1000 else '0' + a[:3]

print(stringtoZ(3), stringtoZ(123), stringtoZ(1234))
# 0003 0123 0123

Another approach is what jarmod mentioned in the comment:

def stringtoZ(n):
    return str(n).zfill(4) if n < 1000 else str(n//10).zfill(4)
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

If you want to check for valid input, try

def z(n):
    if -1 < n < 1000  : return ('000'+str(n))[-4:]
    if -1 < n < 10000 : return '0'+str(n//10)
    raise ValueError('n = %d is out of range (0 ≤ n < 10000).'%n)

The first if catches all the n < 1000 numbers and returns the tail of a a longer string.

The second if catches all the numbers in 999 < n < 10000 and uses integer division (the // operator) to remove the last digit.

The raise statement is reached only if n is outside the valid interval, so we can raise an exception (ValueError seems appropriate), providing also an error message for the caller.

Having previously defined z(n) in the interpreter we have

In [32]: z(4567)
Out[32]: '0456'

In [33]: z(567)
Out[33]: '0567'

In [34]: z(20000)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-3a36d9b24c14> in <module>
----> 1 z(20000)

<ipython-input-26-d5602c2c4b24> in z(n)
      2     if -1 < n < 1000  : return ('000'+str(n))[-4:]
      3     if -1 < n < 10000 : return '0'+str(n//10)
----> 4     raise ValueError('n = %d is out of range (0 ≤ n < 10000).'%n)

ValueError: n = 20000 is out of range (0 ≤ n < 10000).

And eventually an example of how one can manage the exception in their code:

In [35]: for n in (-1, 0, 1, 999, 9999, 10000):
    ...:     try:
    ...:         print('%8d ——→'%n, z(n))
    ...:     except ValueError as e:
    ...:         print(e)
n = -1 is out of range (0 ≤ n < 10000).
       0 ——→ 0000
       1 ——→ 0001
     999 ——→ 0999
    9999 ——→ 0999
n = 10000 is out of range (0 ≤ n < 10000).

In [36]:
gboffi
  • 22,939
  • 8
  • 54
  • 85