Python 将整数转换为字符串的过程(“引擎盖下”)

Python 将整数转换为字符串的过程(“引擎盖下”),python,string,type-conversion,integer,Python,String,Type Conversion,Integer,我是Python新手,在理解如何使用Python方面面临着一个真正的问题 str(123)或int('123')函数工作 我试着检查builtins.py,但是有一些函数和方法我不理解。这都是关于二进制转换的吗 作为一个错误的例子: str(123)=>bin(123)->1111011->1100101+1111011+1010101->与一些表格比较 有什么简单的解释或文章可以帮助你吗? str(),int()如何实现他们的“转换魔法”?如果你用Python的风格回答我会很完美,但这并不可怕

我是Python新手,在理解如何使用Python方面面临着一个真正的问题
str(123)
int('123')
函数工作

我试着检查builtins.py,但是有一些函数和方法我不理解。这都是关于二进制转换的吗

作为一个错误的例子:

  • str(123)
    =>
    bin(123)
    ->
    1111011
    ->
    1100101+1111011+1010101
    ->
    与一些表格比较
  • 有什么简单的解释或文章可以帮助你吗?
    str()
    int()
    如何实现他们的“转换魔法”?如果你用Python的风格回答我会很完美,但这并不可怕

    <> C++中的文章,超出我的经验:

  • 试图通过将数字
    number/10
    number%10
    分开来解释此过程的文章:

  • 字符串到整数 让我们从将字符串转换为int开始,因为我认为这更容易理解。首先,我将做一些假设:

  • 我们的int方法目前只处理int输入、无浮点、复数等
  • 我们现在也只讨论正数
  • 我不会处理故意错误的输入,比如int(“Wassup”)
  • 实现将从右到左遍历字符串输入,并按数字构建整数

    def custom_int(input):
        # Your intuition is right that we will need some kind of look up! this matches a character to a number
        s_to_i_dict= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        
        # imagine our input is the string "123", we want to build up the number 123 
        # one digit at a time. If you break it down, 123 is equal to 100 + 20 + 3
        # Thinking it through further, that's the same as 1*100 + 2*10 + 3*1
    
        # So for each digit going right to left, we'll multiply it by some multiplier
        # add it to our result, theb change that multiplier to handle the next digit.
        
        multiplier = 1
        output = 0
    
        # This is a little shortcut to get you looping through a list or a string from the last element to the first:
        for digit in input[::-1]:
            # digit is a character, we find the corresponding number, multiply it by the multiplier, then add it to the old version of output
            output = output + ( s_to_i_dict[digit] * multiplier)
    
            # we are done with this digit, so the next multiplier should be 10 times the last (going from digits to tens to hundreds etc.)
            multiplier = multiplier * 10
        return output
    
    运行此功能,您将获得:

    s_to_i(“123”)

    123

    类型(s_至_i(“123”))

    对于“123”输入,我们的循环将运行3次。第一次输出将是最右边的数字3,下一次,我们将在输出中添加2*10,得到23

    最后一次通过循环我们将得到23+1*100,或123

    整数到字符串 我们可以将完全相同的模式应用于int-to-string转换。同样的假设也适用,因为我不会涵盖所有的边缘情况,但基本上我们会做相同的事情:从右到左遍历数字,然后构建数字的字符串表示形式

    现在我们不能像在字符串上循环那样简单地循环数字,但是通过使用mod和division,我们可以得到类似的模式。假设n=123,我们如何从数字中得到最右边的数字?最右边的数字是n除以10的余数,或者在代码中最右边的数字=n%10

    一旦我们有了最右边的数字,下一步就是尝试提取第二个最右边的数字,在本例中为2。有几种方法可以做到这一点,但我最喜欢的是认识到,我们已经抓住了最右边的数字,所以我们不再需要它了

    我们可以将数字n更新如下:
    n=n//10
    这将使n的值为12而不是123。这叫做整数除法,基本上是小学除法,在你发现浮点数之前:P

    这有什么帮助?注意,2是12的最右边的数字,我们已经知道如何抓住它了!让我们把这些放在一个函数中

    def i_to_s(input):
      # Notice that this is the opposite dictionary than before. ints are the key, and they give us the character we need.
      i_to_s_dict={0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
      
      # This time we want our output to be a string so we initialize an empty string
      output = ""
      
      # There are more precise ways to set up this loop, as this one creates an edge case I'll leave up to you to find, but works with _almost_ every integer :P
      while(input != 0):
    
        rightmost_digit = input % 10
        
        # We concatenate the new character we found with the output we've accumulated so far
        output = i_to_s(rightmost_digit) + output
        
        # Change the initial number for the next iteration
        input = input // 10
      
      return output
    
    i_至_s(123)

    ‘123’

    类型(i_至s(123))


    您是否检查了这些类是如何实例化的?例如,是的,但表示如果一切正常,则返回
    对象。这里-->“和内置函数format()和print()来计算对象的“非正式”或可良好打印的字符串表示形式。返回值必须是字符串对象。”看起来像一个圆圈。实际上,这是有意义的。类的
    \uuuu str\uuuu
    方法返回其字符串表示形式,当调用该类的实例时,
    print()
    (以及
    str()
    )将返回该字符串表示形式。也许尝试一下Python的OOP并创建您的第一个类会有所帮助。这是一种真正的方法吗?我的意思是,它拥有一个类似于你上面提到的值字典的
    I_to_s_dict
    ,增加了一些处理函数,就这样?反正听起来不错!如果我想更深入地挖掘。。。在哪里可以找到这个源代码?或者它是C++/CPython代码,现在我还不明白?谢谢你的解释!我一直在试图找到int类定义str的地方,反之亦然,但我没有运气,它变得非常复杂。我无法跟踪int的具体实现,但可以继续研究。源代码在这里:@m.oulmakki请看这里:简而言之,Python将整数中的二进制分支数组转换为十进制数字组:通常,它从基
    2**30
    转换为基
    10**9