【问题标题】:Do not strip White spaces at the beginning or end of a text - Python不要在文本的开头或结尾去除空格 - Python
【发布时间】:2019-04-08 16:50:09
【问题描述】:

我在 Python 中有这段代码,可以将十进制转换为其对应的 ASCII 字符。

import codecs
def convert_decimal_to_string(decrypted):
    decrypted = hex(decrypted)
    decrypted = decrypted.replace('0x', '')        
    return codecs.decode(codecs.decode(decrypted,'hex'),'ascii')

decrypted = 1612388154947973357665
decrypted = convert_decimal_to_string(decrypted)
print(decrypted + 'Creel?')

输出应该是“什么是纱架?”不是“什么是纱架”。如何在文本的开头或结尾保留空格?

【问题讨论】:

  • 您的输入错误:>>> '\x57\x68\x61\x74\x20\x69\x73\x20\x61' 'What is a'。代码不能弥补不存在的空间。
  • @GiacomoAlzetta --> 谢谢,我的代码中一定有问题。我稍后会更新它。
  • @GiacomoAlzetta --> 您可以将您的评论放在答案部分,以便我将其标记为正确答案。我已经解决了我的问题。你的想法让我搜索到我的代码的另一部分。谢谢

标签: python python-3.x trim removing-whitespace


【解决方案1】:

您的输入末尾缺少空格:

>>> hex(1612388154947973357665)
'0x576861742069732061'
>>> # manually add \x for every pair of digits:
>>> '\x57\x68\x61\x74\x20\x69\x73\x20\x61'
'What is a'

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多