📌  相关文章
📜  Python - 反转一行中的单词并保持特殊字符不变

📅  最后修改于: 2022-05-13 01:55:03.373000             🧑  作者: Mango

Python - 反转一行中的单词并保持特殊字符不变

反转一行中所有单词中的字符,包括数字,但在同一位置保留特殊字符和符号不变。考虑以下示例。

看上面的例子,每个单词都被反转,如果有任何特殊字符,那么特殊字符周围的单词被反转。

Python3
def reverStringsInLine(s):
   
    sl = s.split(' ')
    rsl = ''
     
    for word in sl:
        str_word = ''
        rev_sub_word = ''
         
        for ch in word:
             
            if ch.isalnum():
                str_word += ch
             
            else:
                 
                # If it is special character, then
                # reverse non special characters and
                # append special character
                 
                rev_sub_word += str_word[::-1] + ch
                 
                # Clear the old stached character, as
                # it is already reversed
                str_word = ''
         
        # Keep appening each words, also add words
        # ending with non-special character
        r_word = rev_sub_word + str_word[::-1]
        rsl += r_word + ' '
    return rsl
 
 
s = 'Bangalore is@#$!123locked locked again in jul2020'
 
print(reverStringsInLine(s))


输出:

erolagnaB si@#$!dekcol321 dekcol niaga ni 0202luj