反转除标点符号以外的每个单词而不改变它们的位置 - Python3

Reverse each word except punctuation(s) without altering their position - Python3

我正在尝试解决以下问题#PROBLEM DEFINITION -

  1. 反转输入字符串中的每个单词。
  2. 词序不变
  3. 一个单词由字母and/or个数字组成。
  4. 其他字符(空格、标点符号)不会被反转

但是,我无法满足保持命令生效的要求。下面是我的代码。任何帮助将不胜感激。

提供: 输入字符串 = 'Hello! cu2 Ayaan...'

预计: 输出字符串 = 'olleH! 2uc naayA...'


def swap(a, b):
    return b, a

def reverse_each_word(sentence):
    list_of_string = [i for i in sentence]
    r = len(list_of_string) - 1
    l = 0
    while l < r:
        if not list_of_string[l].isalpha():
            l += 1
        elif not list_of_string[r].isalpha():
            r -= 1
        else:
            list_of_string[l], list_of_string[r] = swap(list_of_string[l], list_of_string[r])
            l += 1 
            r -= 1
    result = "".join(list_of_string)
    return result

辛苦了。你快到了。恭喜。我对你的代码做了最小的改动。我所做的就是将句子拆分成单词(然后拆分单词的每个字符)并将您的反转逻辑应用于每个拆分的单词列表。还缺少 ..isdigit() 支票,因为根据先决条件 3,单词可以由字母和数字组成。就这样。剩下的就是你的代码。

我假设单词由 1 个空格分隔,并且只有 1 个空格。如果不是请使用 re 模块。

下面是代码。有什么不懂的请追问

def swap(a, b):
    return b, a

def reverse_each_word(sentence):
    list_of_string = [i for i in sentence.split(" ")]
    Finalresult = ""
    for eachString in list_of_string:
        eachString = [x for x in eachString]
        r = len(eachString) - 1
        l = 0
        while l < r:
            if not (eachString[l].isalpha() or eachString[l].isdigit()):
                l += 1
            elif not (eachString[r].isalpha() or eachString[r].isdigit()):
                r -= 1
            else:
                eachString[l], eachString[r] = swap(eachString[l], eachString[r])
                l += 1 
                r -= 1
        result = "".join(eachString)
        Finalresult += (result+" ")
    return Finalresult

print(reverse_each_word( 'Hello! cu2 Ayaan...'))

输出为

olleH! 2uc naayA...

@Amit - 谢谢鼓励!!回去阅读了整个 REGEX 文档(最后)。结果,我用很少的代码行数解决了这个问题。下面是代码 -

import re

def reverse_word(sentence):
    temp = ""
    pattern = re.compile(r'(\W+)')
    result = pattern.split(sentence)
    for i in result:
        p = re.compile("^[a-zA-Z0-9]+$") 
        if p.match(i):
            i = i[::-1]
        temp += i
    return temp