Dane
Dane

Reputation: 19

Python Slicing operator not recognizing number 0

Can anyone explain to me why this isn't giving me the right output when the array value 0 is in the start position of the slicing operator. The following code gives me the right output:

array = [1, 0, 3, 1, 5, 6, 7, 8, 9, 0]

x = int(''.join(str(i) for i in array))
print("x = ",x)
a = int(str(x)[:3])  
print("a = ",a)
b = int(str(x)[3:6])
print("b = ",b)
c = int(str(x)[6:10])
print("c = ",c)

output:

x = 1031567890

a = 103

b = 156

c = 7890

now if I change the first value of the array to a zero [0, 0, 3, 1, 5, 6, 7, 8, 9, 0] it will skip the first 2 zeros but will still display the last zero of the array

output:

x = 31567890

a = 315

b = 678

c = 90

Same behaviour if I change the 4th position to a zero which is the start of the second slicing operator [1, 0, 3, 0, 5, 6, 7, 8, 9, 0] output:

x = 1030567890

a = 103

b = 56

c = 7890

Thank you

Upvotes: -1

Views: 302

Answers (2)

Gregy8
Gregy8

Reputation: 94

This is expected behavior since:

  • the ''.join(str(i) for i in array) will evaluate as '0031567890'
  • the function int('0031567890') will give the int 31567890 (removing leading 0's in the process)
  • Converting back to string with str(31567890) will give '31567890'
  • doing slicing on it and convert it back to int will always remove the leading 0's

So your problem is that you expect integer datatype to have leading 0's but it dont. If you want to display numbers with a fixed length you need to convert them to string and apply a padding in front of them so that they all have the same length, but lot of things can hapend in the process and that is a display considerartion. So it's a whole new problem please checkout this question How to pad zeroes to a string?.

Upvotes: 1

user11531820
user11531820

Reputation:

Since you are converting list to int variable python will remove all the leading zeroes before a non zero value.

So in your case:[0, 0, 3, 1, 5, 6, 7, 8, 9, 0] -> 0031567890 -> 31567890(leading zeroes add no value to integers).

But since zeroes occurring after any non zero char adds to value of the integer it won't be removed by python.

[0, 0, 3, 1, 5, 6, 7, 8, 9, 0] -> 0031567890 -> 31567890(if we remove last zero then value changes to 3156789 which is a different integer).

Upvotes: 0

Related Questions