Home>

I'm new to programming.
I want to invert the number 12345 in Python like 54321 and display it.

Error message: ValueError: invalid literal for int () with base 10:''
Is displayed and it does not work
Can you tell me what was wrong with me?
Corresponding source code
num = 12345
str_num = str (num)
x = 0
lis = []
while x<6:
    amari = int (str_num [0: 5-x])% 10
    lis.append (amari)
    x + = 1
print (lis)
result =''. join ([lis])
print (result)
What I tried

I wonder if int (str_num [0: 5-x]) is treated as a decimal number.
'{: d}'. format (int (str_num [0: 5-x]))
I converted it as, but this is also
TypeError: not all arguments converted during string formatting
I got an error

Supplementary information (FW/tool version, etc.)

It is a web learning service called PyQ

  • Answer # 1

    amari = int (str_num [0: 5-x])% 10
    In the above place, when x becomes 5, it becomes str_num [0: 0], which is an empty string.

    Postscript
    It seems that the character string can be inverted with str_num [:: -1].

  • Answer # 2

    It depends on what the code is for, but if you want to do what you want, it's already in the answer.str_num [:: -1]I think it's smart.

    If the purpose is to learn algorithms, etc., it can be realized by recursive call of the function.

    num = 12345
    def func (n, l):
        if n<10:
            l.append (n)
            return;
        l.append (n% 10)
        n = n // 10
        func (n, l) # recursion
    list1 = []
    func (num, list1)
    print (list1) # [5, 4, 3, 2, 1]
    r =''. join ([str (item) for item in list1])
    print (r) # 54321

Trends