Click here to Skip to main content
15,665,276 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I got the correct output but I need an optimised solution for this.

input:
I* Am Not String

output:
g* ni rtS toNmAI

What I have tried:

a = input()
b = a[::-1]
op = 65
po = 97
c = []
j = 0
for i in b:
    if (i>=chr(op) and i<=chr(op+25)) or (i>=chr(po) and i<=chr(po+25)):
        c.append(i)
for i in range(0,len(a)):
    if (a[i]>=chr(op) and a[i]<=chr(op+25)) or (a[i]>=chr(po) and a[i]<=chr(po+25)):
        print(c[j],end='')
        j+=1 
    else:
        print(a[i],end='')
Posted
Updated 29-Mar-22 11:48am
Comments
Richard MacCutchan 29-Mar-22 3:56am    
Do not use numbers (65, 97) to represent characters, it makes the code difficult to read. Use the proper characters ('A', 'a'). The optimised solution would be to swap elements from the first character to the hals-way point.
shri harshan 29-Mar-22 7:58am    
Thank you

1 solution

Try this:

Python
def reverse(input_str):
    new_str = input_str.replace(' ','').replace('*','')[::-1]
    index = 0
    for c in input_str:
        if c == ' ' or c == '*':
            new_str = new_str[:index] + c + new_str[index:]
        index +=1
    return new_str

txt = "I* Am Not String"
print(txt) 
print(reverse(txt)) 
 
Share this answer
 
Comments
CPallini 30-Mar-22 2:36am    
5.
Maciej Los 30-Mar-22 6:33am    
Thank you, Carlo.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900