Pergunta

Is there any good idea how to get the second digit of a string? For example:

aaa = 122
bbb = 333

rest = bbb-aaa 
if rest[:2] == 1: 
    do something..
Foi útil?

Solução

Convert the integer to a string first using the built-in str() function and then slice it accordingly

So Try this:

if str(rest)[1] == '1':
    #do something example:
    print 'hi'

Outras dicas

Index it:

>>> mystr = "123"
>>> mystr[1]
'2'
>>> mystr[-2]
'2'
>>>

If it is a number, then you need to convert it to a string first with str:

>>> myint = 123
>>> str(myint)[1]
'2'
>>> str(myint)[-2]
'2'
>>>

def lastsecond(num):

if(num>-9 and num<10):
    return -1;
else:
    temp=num/10;
    rem=temp%10;
    return int(rem);

number=abs(int(input("enter number : "))) print("the last second digit of %d is %d"%(number,lastsecond(number)))

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top