How to convert an int number to string in python?

3

I need to do an exercise in which I ignore an integer variable of 3 digits and python has to show it inverted, but until where I know an integer variable can do that, but a string yes. What can I do?

    
asked by anonymous 23.03.2017 / 19:15

3 answers

5

You can use:

str(10);

And string to int you can use:

int('10');
    
23.03.2017 / 19:19
4

To reverse the string that returns from input() , which already returns a string and not an integer, you can do this:

num = input("introduza um num") # '123'
revertido = num[::-1]
print(revertido) # '321'

DEMONSTRATION

But to transform an integer into a string and revert would be:

str(123)[::-1] # '321'

As mentioned in other answers.

And to have this reversion again in integer:

int(str(123)[::-1]) # 321
    
23.03.2017 / 19:29
2

When you say

  

I'm guessing an integer variable of 3 digits

Interpreted as

  

I read from the standard input an integer

If you are using Python 3, you read from the standard input with the function input , with the return always being a string. So, reversing the number would reverse the string. If you are using Python 2, the input function will return a number, but you could use raw_input , which returns a string.

Documentation:

Interpreting as a function in which a number will be sent, you can convert it to string according to David Melo's response >.

Interpreting how to do this inversion using only mathematical operations, you can use the module and the entire division.

For example, in Python 3:

a = 123 # número a inverter
b = 0 # número invertido

for i in range(3):
    # pegue o último dígito de 'a' e coloque após os valores atuais de 'b'
    b = b*10 + (a % 10)
    # remova o último dígito de 'a'
    a = a//10
print(b)
    
23.03.2017 / 19:41