反转字符串中的字母(但不包括非字母),同时保留原始大小写

时间:2019-01-28 20:26:20

标签: python python-3.x

例如句子:

'God bless our brave Confederates, Lord!'

...应该是:

'Dro lseta red efnoc Evarbruossel, Bdog!'

我的代码当前为:

def reversing(sentence):
    code = []
    for l1, l2 in zip(sentence, sentence[::-1]):
        if l1.isalpha() and l2.isalpha():
            l2 = l2.upper() if l1.isupper() else l2.lower()
        code.append(l2)
    return ''.join(code)

但这并不完全正确:

>>> reversing('God bless our brave Confederates, Lord!')
'!drol ,setaredefnoc Evarb ruo sselB doG'

2 个答案:

答案 0 :(得分:1)

我的解决方案产生了预期的效果,但是在同一列表上确实有重复两次的缺点。如果为此的实际应用将花费大量时间,那么从执行时间的角度来看,该解决方案将不是最佳解决方案。

def reversing(sentence):
    parts = list(sentence)
    code = []

    # first iteration reverses only the letters
    for enum, value in enumerate(parts):
        character = sentence[-1 - enum].lower()

        if character.isalpha():
            code.append(character)

    # second iteration formats and inserts non-letters
    for enum, value in enumerate(parts):
        if value.isalpha() and value.isupper():
            code[enum] = code[enum].upper()
        elif not value.isalpha():
            code.insert(enum, value)

    return ''.join(code)

答案 1 :(得分:0)

基于堆栈和队列的简单解决方案

a= 'God bless our brave Confederates, Lord!'

stack=[] # to keep characters
queue=[] # to keep special chars
for i in a:
    if i.isalpha():
        stack.append(i)
    else:
        queue.append(i)

遍历原始字符串以查找并检查char是否在上面,并且不是特殊的char

string=''
for i in a:  
    if i.isalpha():
        if i.isupper():
            string += stack.pop(-1).upper() # change from lower to upper char based on original string
        else:
            string += stack.pop(-1).lower()
    else:
        string += queue.pop(0)
print(string)

输出

'Dro Lseta red efnoC Evarbruossel, Bdog!'