【问题标题】:How to convert a string to a list in Python?如何在 Python 中将字符串转换为列表?
【发布时间】:2022-01-30 15:23:59
【问题描述】:

所以我在这里有这个 Python 代码:

for binary_value in binary_values:
    an_integer = int(binary_value, 2)
    ascii_character = chr(an_integer)
    ascii_string += ascii_character
        if len(ascii_string) == 151:
            print(ascii_string)

它将我的二进制代码转换为文本,它应该将二进制转换为的文本是一串数字,它是以十进制编码的文本。这是小数点(不是我用来展示的实际小数点):

72 101 121 32 116 104 101 114 101 33

问题是它是一个字符串,我需要它是一个整数列表,看起来像这样:

decimal=[72,101,121,32,116,104,101,114,101,33]

我将如何实现这一目标? 谢谢!

【问题讨论】:

  • 假设您的问题陈述中有72 101 121 32 116 104 101 114 101 33 作为字符串,您需要将其转换为int decimal=[72,101,121,32,116,104,101,114,101,33] 的列表。 tmp = 你可以试试这个decimal = list(map(int, tmp.split()))
  • 请使用binary_values 的示例更新您的代码。另外,ascii_string 是什么?

标签: python list encoding integer decimal


【解决方案1】:

这应该可以解决问题:

s = '72 101 121 32 116 104 101 114 101 33'
a = list(map(int, s.split()))
print(a)

输出:

[72, 101, 121, 32, 116, 104, 101, 114, 101, 33]

【讨论】:

    【解决方案2】:

    以下代码 sn-p 可能会有所帮助:

    binary_values = [ '0b1001000', '0b1100101', '0b1111001', '0b100000', '0b1110100', '0b1101000', '0b1100101', '0b1110010', '0b1100101', '0b100001' ]
    decimals = [ int(binary_value, 2) for binary_value in binary_values ]
    print( decimals )
    
    [72, 101, 121, 32, 116, 104, 101, 114, 101, 33]
    

    检查:

    print( ''.join( [ chr(x) for x in decimals ] ) )
    
    'Hey there!'
    

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2016-11-09
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多