Home > other >  Write a program to input a line of text and create a new line of text where each word of input line
Write a program to input a line of text and create a new line of text where each word of input line

Time:12-31

This question is in my book and when I tried to make it in python, the program is showing error.

a=input("Enter the line: ")

W=''

s=a.split()

for i in s:

    q=len(i)

    for b in range(q-1,-1,-1):

        w=w b ' '

print(w)

CodePudding user response:

I'm not quite sure what you were trying to do with that loop, but I'd split the line by space, reverse every word using a slice ([::-1]) and join them back together:

text = input("Enter the line: ")
result = ' '.join(word[::-1] for word in text.split(' '))
print(result)

CodePudding user response:

Disregarding the purpose of this code, you have a couple of errors:

  • Python is case sensitive, you initialized a var called W at the start but then started to use w in the rest of the code
  • w=w b ' ' will throw an error since b is an int, cast it to string w=w str(b) ' '
  • Related