Home > Back-end >  How to separate a 10 digit number into 3 variables?
How to separate a 10 digit number into 3 variables?

Time:07-18

I want to take a 10 digit number and separate it into 3 different variables.

Also big help if you could suggest a way to do this to a multiple number list.

I was going too try a while loop but was looking for any other suggestions.

number = "1234567890"


#The output Im looking for

1 = 123
2 = 456
3 = 7890

CodePudding user response:

I think you can do it very easily by converting your number into a string like this :

your_number = 1234567890

def split_in_3(number):
    number = str(number) # we convert the number into a string
    nb_list = []
    for i in range(2):
        nb_list.append(int(number[:3])) # we take the last three characters of our string and we put them into the list. Don't forget to convert them into integers
        number = number[3:] # we take off the last three digits of the nb and put it in the number variable
    nb_list.append(int(number)) # we add the final part (4 digits) to the list
    return nb_list

print(split_in_3(your_number))

You can return your splited numbers in a tuple or separatly, I did it with a list just as an example

CodePudding user response:

You can do this simply like this:

number = 1234567890

number = str(number)
a = number[:3]
b = number[3:6]
c = number[6:]
  • Related