Fenomatik Fenomatik - 8 days ago 6
Python Question

Last character of string not being picked up

Trying to solve the problem where I can reverse each word in a string , Since there is no "\0" in python unlike C, My logic is failing to pick up the last character of the string.
Any idea how can this be fixed with not too many changes to the code

Input = This is an example
Output = sihT si na elpmaxe

import os
import string

a = "This is an example"
temp=[]
store=[]
print(a)
x=0
while (x <= len(a)-1):

if ((a[x] != " ") and (x != len(a)-1)):
temp.append(a[x])
x += 1

else:
temp.reverse()
store.extend(temp)
store.append(' ')
del temp[:]
x += 1

str1 = ''.join(store)
print (str1)


My output is truncating the last character

sihT si na lpmaxe

Answer

You have remove -1 in both len(a)-1 and change order in and (so when x == len(a) it will no try to get a[x] which could give "index out of range")

while (x <= len(a)):

     if (x != len(a)) and (a[x] != " "):

Full version which works for me

import os
import string

a = "This is an example"
temp = []
store = []
print(a)

x = 0

while (x <= len(a)):

    if (x != len(a)) and (a[x] != " "):
        temp.append(a[x])
        x += 1
    else:
        temp.reverse()
        store.extend(temp)
        store.append(' ')
        del temp[:]
        x += 1

str1 = ''.join(store)
print(str1)
Comments