reverse words in a sentence pythonic

后端 未结 3 909
梦谈多话
梦谈多话 2020-12-22 05:38

I am trying write pythonic code to reverse the words in a sentence

ex:

input: \"hello there friend\"

output: \"friend there hello\"
<
相关标签:
3条回答
  • 2020-12-22 06:20

    You're calling the swap/split in the wrong order. Use this instead:

    w = self.swap(s.split())
    

    Then your return shouldn't need to do any comprehension:

    return ' '.join(w)
    
    0 讨论(0)
  • 2020-12-22 06:31

    Another one

    def revereString(orgString):
      result = []
      splittedWords = orgString.split(" ")
      for item in range(len(splittedWords)-1, -1, -1):
        result.append(splittedWords[item])
      return result
    
    print(revereString('Hey ho hay'))
    
    0 讨论(0)
  • 2020-12-22 06:40

    While there's not a whole lot wrong with wrapping it in a class, it's not exactly the most pythonic way to do things. Here's a shorter version of what you're trying to do:

    def reverse(sentence):
        return ' '.join(sentence.split()[::-1])
    

    Output:

    In [29]: reverse("hello there friend")
    Out[29]: 'friend there hello'
    
    0 讨论(0)
提交回复
热议问题