How to use Python 3 repr, rjust, etc.

Asked 2 years ago, Updated 2 years ago, 41 views

I'm a programming beginner studying the Python3 tutorial.
I am posting because I have not had the same question in the past.
Tutorial 7.1.3. I am having trouble understanding the following example in the manual format of the string.

 for x in range (1,11):
     print(repr(x).rjust(2), repr(x*x).rjust(3), end=')
     # Note use of 'end' on previous line
     print(repr(x*x*x).rjust(4))

# output result
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

I have looked into various features including repr and rjust, but I do not understand the meaning of the whole code.
I look forward to hearing from you.Thank you for your cooperation.

python python3

2022-09-30 19:52

1 Answers

If you don't understand the meaning of the entire code, you may be able to understand the meaning by dividing the code and examining its behavior.

If the tutorial is going this far, you will know for and range, so I will skip the explanation.

 for x in range (1,11): print(x)#In variable x, put int from 1 to 10 and turn the loop

Next, str.rjust displays the string in a right-aligned manner, as described in the description.
Also, print can have multiple arguments separated by commas.

print("a")
#a
print("a".rjust(3))
#  a
print("a", "b".rjust(3), "c")
#abc

The note "One space between each column" in the tutorial explains why "bc" spaces are automatically inserted.

Now, the reason I use repr is because I cannot use str.rjust without repr.
The variable x comes in descending order of int type integers created from range, but rjust only supports str type strings, and when used for int, the SyntaxError error occurs.
By converting int type from repr to str type, you can use str.rjust.

 "1".rjust(3)
#'  1'
repr(1).rjust(3)
#'  1'
1.rjust(3)
# SyntaxError: invalid syntax

By the way, rewriting repr(x) to str(x) works fine, but becomes more difficult, so you can think of it as almost the same now.

x*x is the square of x, and x*x is the square of x.
The square of 2 and the square of 3 are 4,8, so try to run the code close to the tutorial in an array that contains only [2].
Without end=', a new line came in.
This is because if end=' is not specified in print, the line feed of end='\n' is automatically supplemented.

 for x in [2]:
    print(repr(x).rjust(2), repr(x*x).rjust(3))
    print(repr(x*x*x).rjust(4))
# 2   4
#   8

for x in [2]:
    print(repr(x).rjust(2), repr(x*x).rjust(3), end=')
    print(repr(x*x*x).rjust(4))
# 2   4    8

for x in [2]:
    print(repr(x).rjust(2), repr(x*x).rjust(3), end='end')
    print(repr(x*x*x).rjust(4))
# 24 End 8

Now that you know the above characteristics, you can see that the meaning of this entire code is 7.1.2.String format() method using repr or rjust.


2022-09-30 19:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.