python-3.x 反转字符串而不影响特殊字符

yb3bgrhw  于 2023-01-27  发布在  Python
关注(0)|答案(7)|浏览(156)

我试图在不影响特殊字符的情况下反转字符串,但没有成功。下面是我的代码:

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
k2arahey

k2arahey1#

请尝试以下代码:

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))

希望这能起作用...

svujldwt

svujldwt2#

或者用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
cwtwac6a

cwtwac6a3#

你是说像这样吗?:

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()
mxg2im7a

mxg2im7a4#

def reverse_string_without_affecting_number(text):
    temp = []
    text = list(text)
    for i in text:
        if not i.isnumeric():
            temp.append(i)
    reverse_temp =  temp [::-1]
    count = 0
    for i in range(0,len(text)):  
        if not text[i].isnumeric():
            text[i] = reverse_temp[count]
            count +=1  
        else:
            continue
    return "".join(text)
    
print (reverse_string_without_affecting_number('abc1235de9f15ui'))
uinbv5nw

uinbv5nw5#

下面是PHP中的解决方案。

$str = '@ab-cd@y@@rr';
$str_without_char = '';

for($i= 0; $i <= (strlen($str)-1); $i++){
    
    if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $str[$i]))
    {
        $char_index_arr[$i] = $str[$i];
    }else{
        $str_without_char .= $str[$i];
    }
}

$reverse_str_without_char = strrev($str_without_char);

$result = '';
$min = 0;
for($i= 0; $i <= (strlen($str)-1); $i++){
    if(isset($char_index_arr[$i])){
        $result .= $char_index_arr[$i];
        $min++;
    }else{
        $result .= $reverse_str_without_char[$i - $min];
    }
    
}

print($result);
c8ib6hqw

c8ib6hqw6#

def reverse_with_out_changing_special_char(data):
    count = 0
    dictt = {}
    char_only = []
    for i in data:
        if not i.isalpha():
            dictt.update({count : i})
        else:
            char_only.append(i)
        count = count +1

    reverse_char_only = char_only[::-1]
    for key, val in dictt.items():
        reverse_char_only.insert(key, val)
    
    return reverse_char_only

if __name__ == '__main__':
    data = 'PQADr@%bh$%$%u'
    reverse_char_only = reverse_with_out_changing_special_char(data)
    print ("".join(reverse_char_only))
cczfrluj

cczfrluj7#

def反向字符串(t):c=[] t=列表(t),i在t中:如果i是alpha():c.对于范围(len(t))中的i,append(i)反向字符串= c[::-1]计数= 0:如果不是t[i]. is alpha():reverse_string.insert(i,t[i])返回反向字符串打印(反向字符串(“a@bc%d”))

相关问题