简体   繁体   English

查找任何给定数字的第 n 位数字

[英]Finding the nth digit of any given number

I'm very new to python, and I'm trying to write a program that will find the nth digit of any given positive integer from the right.我对python很陌生,我正在尝试编写一个程序,该程序将从右侧找到任何给定正整数的第n位数字。 How would I go about this?我该怎么办? I'm at a bit of a loss as to where I should start.我不知道应该从哪里开始。 I saw an answer to a similar question suggesting code, and it seemed to work for the op.我看到了一个类似问题的答案建议代码,它似乎适用于操作。 When I tried it, it just returned the number and specified digit as an ordered pair.当我尝试它时,它只是将数字和指定的数字作为有序对返回。 This is that code:这是代码:

def get_digit(number, n)
    return number // 10** % 10

This formula will give you the nth digit of a number:这个公式会给你一个数字的第 n 位:

def get_digit(number, n): 
     return number // 10**(n-1) % 10 

get_digit(153443, 2)                                                                                                                                                                
# 4

or by converting to string:或通过转换为字符串:

def get_strdigit(num, offset):
   num = str(num)
   return num[offset+1]

get_strdigit(33434324,2)                                                                                                                                                            
# '3'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM