How to reverse only the alphabetic characters in a string, keeping other characters in place with Python

1 Answer

0 votes
def reverse_only_alphabetic_characters(s: str) -> str:
    chars = list(s)
    i, j = 0, len(chars) - 1

    while i < j:
        if not chars[i].isalpha():
            i += 1
        elif not chars[j].isalpha():
            j -= 1
        else:
            chars[i], chars[j] = chars[j], chars[i]
            i += 1
            j -= 1

    return "".join(chars)


s = "a1-bC2-dEf3-ghIj"

print(s)
print(reverse_only_alphabetic_characters(s))



'''
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

'''

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...