【问题标题】:How would I reverse each word individually rather than the whole string as a whole我将如何单独反转每个单词而不是整个字符串
【发布时间】:2017-11-07 06:45:29
【问题描述】:

我正在尝试单独反转字符串中的单词,因此单词仍然按顺序排列,但是只是反转了,例如“hi my name is”,输出为“ih ym eman si”,但是整个字符串被翻转了

    r = 0
    def readReverse(): #creates the function
        start = default_timer() #initiates a timer
        r = len(n.split()) #n is the users input
        if len(n) == 0:
            return n
        else:
            return n[0] + readReverse(n[::-1])
            duration = default_timer() - start
            print(str(r) + " with a runtime of " + str(duration))

    print(readReverse(n))

【问题讨论】:

  • 你想如何处理标点符号?

标签: python-3.x reverse


【解决方案1】:

首先使用正则表达式similar to this 将字符串拆分为单词、标点符号和空格。然后您可以使用生成器表达式单独反转每个单词,最后将它们与str.join 连接在一起。

import re


text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)

reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)

输出:

olleH, m'I a gnirts!

如果你想忽略标点符号,你可以省略正则表达式,只拆分字符串:

text = "Hello, I'm a string!"

reversed_text = ' '.join(word[::-1] for word in text.split())

但是,逗号、感叹号等将成为单词的一部分。

,olleH m'I a !gnirts

这是递归版本:

def read_reverse(text):
    idx = text.find(' ')  # Find index of next space character.
    if idx == -1:  # No more spaces left.
        return text[::-1]
    else:  # Split off the first word and reverse it and recurse.
        return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])

【讨论】:

  • 当我尝试返回函数 python output 'none' 时,我将如何递归地实现这个
  • 我添加了递归版本。
猜你喜欢
  • 2013-11-13
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多