The function I am writing needs to reverse a string while maintaining the spaces' positions as well as the positions of capitalization. Thus when the input is "I lovE Python" the output will be "N htyP Evoli"
def program(x):
n = len(x)
y = x.lower()
result = [0]*n
for i in range(n):
if x[i] == ' ':
result[i] = ' '
else:
if (x[i].isupper() == True):
if (y[n-i]==' '):
result[i] = y[n-i-1].upper()
else:
result[i] = y[n-i].upper()
else:
if (y[n-i]==' '):
result[i] = y[n-i-1]
else:
result[i] = y[n-i]
return ''.join(str(v) for v in result)
I get an index out of bounds error due to the result[i] = y[n-i-1] code; however, if I don't have that line the code adds an additional space depending on the string.