【问题标题】:How to return a string by concatenating characters in python如何通过在python中连接字符来返回字符串
【发布时间】:2015-06-16 17:53:19
【问题描述】:

我在 Python 2.7 中编写了以下代码

class BinaryCode:
    def decode(self, message):
        result = str(0)
        result += str(message[0])
        for i in range(1, len(message)-1):
            result += str(int(message[i])-int(result[i])-int(result[i-1]))
        return result

当我将消息初始化为 123210122 时,我希望结果为 011100011 但它却是 {"0", "1", "1", "1", "0", "0", "0", " 1”,“1”}。如何做到这一点?

这是一个 topcoder SRM 144 Div 2 问题,这就是结果。

现在,当我在 IDLE 中运行此代码时,它给了我一个字符串,但为什么它在 topcoder 中不起作用?

【问题讨论】:

  • ''.join(result) 就在返回结果之前
  • 我刚刚运行它,它返回011100011(所以这不是您运行的代码,或者这不是您获得的输入)
  • @sunny:为什么会这样?你不认为result 应该是一个字符串吗?
  • 好的,我想通了。他希望结果是二进制数字,而不是字符串。不是很明显,但在运行他的代码后,这是我唯一能得到的解释。
  • 如果我确定message 是一个字符串,那么这工作正常...

标签: python string python-2.7 string-concatenation


【解决方案1】:

只需将函数的最后一行更改为return ''.join(result)

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多