【问题标题】:Reverse Words in String using Python [closed]使用Python反转字符串中的单词[关闭]
【发布时间】:2018-07-09 20:35:35
【问题描述】:
class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        d=[]

        words=s.split()
        for i in words:
            d.append(i[::-1])
            print d
            result=" ".join(d)
        return result

错误:

UnboundLocalError: local variable 'result' referenced before assignment

编辑:-

result=" ".join(d)
print result

当我在最后两行中使用此代码时,我可以看到我的标准输出但返回的是空值,当我使用这两行代替上面的代码时:

result=" ".join(d)
return result

我只得到该行的第一个单词。

例如。 “我在写代码”

预期输出:-“edoc a gnitirw ma I”
实际输出:“edoc”

【问题讨论】:

标签: python string reverse


【解决方案1】:

这里的问题是您只在循环内声明了result。如果您发送一个空字符串,s.split() 将返回一个空列表,result 将永远不会被声明。

for 循环之前用默认值声明 result,这个异常应该会消失。

【讨论】:

  • 我也试过了,但我收到一个错误,提示“超出输出限制”。我在 leetcode 上试过这个。
猜你喜欢
  • 2016-02-19
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
相关资源
最近更新 更多