147875
147875

Reputation: 193

How to break a 1000 digit long integer into mulitple lines in python

For example I have 100 digit integer, which I want to break into multiple lines for better over view.

x = 1000000000
    0000000000
    0000000000
    0000000000
    0000000000
    0000000000
    0000000000
    0000000000
    0000000000
    0000000000

I tried breaking as per pep8, but it's showing invalid syntax error.

Upvotes: 3

Views: 1182

Answers (3)

A45
A45

Reputation: 175

You can use write big numbers like this:

x = 10**n (n being the power)

Another form (reacting to your comment) is:

x = 123 x = x * (10**3) + 456 (3 is a form of n)

Upvotes: 2

Daweo
Daweo

Reputation: 36520

I do not know if it is possible with integers, but you might use / to make multiline str representing number and then convert it to int, i.e.

x = '100\
000\
000'
x = int(x)
print(x)  # 100000000
print(type(x))  # <class 'int'>

(tested in Python 3.7.3)

This naturally means additional operation as opposed to explicit x = 100000000, however that conversion shouldn't be problem, unless your task is ultra-time-critical.

Regarding readibility note that if you use Python 3.6 or newer you might use underscores in numeric literals as PEP 515 says. Speaking simply - you might place _ in numeric literals as long as it is not adjacent to another _ and not leading and not trailing character, so for example all following lines have same effect:

x = 1000
x = 1_000
x = 1_0_0_0

and so on

Upvotes: 1

Joshua Varghese
Joshua Varghese

Reputation: 5202

Let:

x = 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could split it and view:

for i in [str(x)[i:i+10] for i in range(0,len(str(x)),10)]:
    print(i)

Gives:

1000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000

As numbers can't be subscribed, we take the string of the number (x remains unaffected).
To store the output as a string ( as a view of x ):

view_of_x = '\n'.join([str(x)[i:i+10] for i in range(0,len(str(x)),10)])

Now print it:

print(view_of_x)

Upvotes: 0

Related Questions