1

for example i have this variable:

x=123

how can i convert it to a tuple or each digit into separate variables?:

x=(1,2,3)

or

x1=1
x2=2
x3=3
smart
  • 161
  • 1
  • 7

4 Answers4

6
>>> x=123
>>> tuple(map(int, str(x)))
(1, 2, 3)
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
4

You can use a comprehension with a tuple after casting the value to a string:

x=123
x = tuple(int(i) for i in str(x))

Output:

(1, 2, 3)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

Convert to a string, convert each digit to an int, then unpack directly into variables:

x = 123
x1, x2, x3 = [int(i) for i in str(x)]

This requires that you know in advance how many digits are present in the string. Better to just use a tuple or list to hold the digits and reference them by index.

t = tuple(int(i) for i in str(x))
t[0]
# 1
etc.
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

Code:

    x = 1234567
    digits = []

    print("number: " + str(x))

    while x > 0:
        digits.append(x % 10)
        x = int(x / 10)

    # To put it back in order
    digits.reverse()

    for i in range(len(digits)):
        print(digits[i])

Output:

number: 1234567
1
2
3
4
5
6
7