整数转字符串过程("under the hood")

converting Integer to String process ("under the hood")

我是 Python 的新手,在理解方法方面遇到了一个真正的问题 str(123)int('123') 函数有效。

我试图检查 builtins.py 但是有一堆我无法理解的函数和方法。都是关于二进制转换的吗?

作为错误的示例:

  1. str(123) => bin(123) -> 1111011 -> 1100101 + 1111011 + 1010101 -> compare with some-table -> '123'

是否有任何简单的解释或文章可以提供帮助? str()int() 如何发挥他们的 “转化魔法”?如果您以 Python 风格回答我,那将是完美的,但这并不可怕...

超出我经验的 C++ 文章:

  1. Easiest way to convert int to string in C++

  2. http://we.easyelectronics.ru/Soft/preobrazuem-v-stroku-chast-1-celye-chisla.html

试图通过除以数字 number / 10number % 10 来解释这个过程的文章:

  1. How are integers converted to strings under the hood?

字符串转整数

让我们从将字符串转换为 int 开始,因为我认为考虑起来更简单一些。我先做一些假设:

  1. 我们的 int 方法目前只处理 int 输入,不处理浮点数、复数等。
  2. 我们现在也只处理正数。
  3. 我不会处理故意错误的输入,比如 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

type(s_to_i("123"))

<class 'int'>

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

循环的最后一次我们将得到 23 + 1*100,即 123。

整数转字符串

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

现在我们不能像循环字符串那样轻松地循环数字,但是通过很好地使用 mod 和除法,我们可以获得类似的模式。比如说 n = 123,我们如何从数字中得到最右边的数字?最右边的数字是 n 除以 10 的余数 ,或者在代码中 rightmost_digit = 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_to_s(123)

'123'

type(i_to_s(123))

<class 'str'>