不影响特殊字符的反串

问题描述 投票:0回答:3

我试图在不影响特殊字符的情况下反转一个字符串,但它不工作。这是我的代码。

def reverse_each_word(str_smpl):
    str_smpl = "String; 2be reversed..."  #Input that want to reversed 
    lst = []
    for word in str_smpl.split(' '):
        letters = [c for c in word if c.isalpha()]
        for c in word:
            if c.isalpha():`enter code here`
                lst.append(letters.pop())
                continue
            else:
                lst.append(c)
        lst.append(' ')
    print("".join(lst))
    return str_smpl


def main():   #This is called for assertion of output 
    str_smpl = "String; 2be reversed..."  #Samplr input 
    assert reverse_each_word(str_smpl) == "gnirtS; eb2 desrever..."   #output should be like this 
    return 0
python python-3.x string special-characters
3个回答
0
投票

试试下面的代码。

from string import punctuation
sp = set(punctuation)
str_smpl = "String; 2be reversed..."  #Input that want to reversed 
lst = []
for word in str_smpl.split(' '):
    letters = [c for c in word if c not in sp]
    for c in word:
        if c not in sp:
            lst.append(letters.pop())
            continue
        else:
            lst.append(c)
    lst.append(' ')
print("".join(lst))

希望这能奏效...


0
投票

或者试试这个 itertools.groupby,

import itertools

def reverse_special_substrings(s):
    ret = ''
    for isalnum, letters in itertools.groupby(s, str.isalnum):
        letters = list(letters)

        if isalnum:
            letters = letters[::-1]

        ret += ''.join(letters)

    return ret

0
投票

你是说像这样吗?

def reverse_string(st):
    rev_word=''     
    reverse_str=''
    for l in st:
        if l.isalpha():
            rev_word=l+rev_word  

        else:
            reverse_str+=rev_word
            rev_word=''
            reverse_str+=l

    return reverse_str


def main():
    string=' Hello, are you fine....'
    print(reverse_string(string))

if __name__=='__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.