python - 将整数转换为字符串过程 ("under the hood")

标签 python string type-conversion integer

我是 Python 的新手,在理解如何 str(123)int('123') 函数有效。

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

作为一个错误的例子:

  1. str(123) => bin(123) -> 1111011 -> 1100101 + 1111011 + 1010101 -> 与一些表比较 -> '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 输入,不处理 float 、复数等。
  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'>

关于python - 将整数转换为字符串过程 ("under the hood"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67212038/

相关文章:

python - 覆盖 django 管理员身份验证

python - 打开 CV Python- 图像失真径向和透视-

python - 如何使用 Flask 中的 DropDownMenu 获取 MongoDB 中的所有 IdObject

python - 从列表中检测列中的特定字符串序列

c - Stdin + 字典文本替换工具 -- 调试

Python:从字符串元组中获取第一个元素

rust - 使用 '?'运算符对自定义类型进行自动错误转换

c++ - 将 c++ dll 导入 vb.net 时,float*(图像类型)的等效数据类型是什么?

Python UTF-8 无法在 32 位机器上解码字节

python - 与整数差距的季度数