One of the questions on the grok learning python course is, "Write a program that reads in a line of text and prints out the line of text backwards."I wrote:
word = input('Line: ')
for i in range(len(word)):
i = (0 - 1 - i)
print(word[i],end = "")
This gives any entered text back to the user backwards but when I submit it it says "Your output is missing a trailing newline character." Does this mean that the answer is incorrect because any new print statements will print text on the same line as the entered word?
What I would do is store the reverse of the word in another variable new_word
and then print that after the for loop.
word = input('Line: ')
new_word = ""
for i in range(len(word)):
i = (0 - 1 - i)
new_word += word[i]
print(new_word)
Obligatory one-liner:
>>> "This is my string in reverse"[::-1]
'esrever ni gnirts ym si sihT'
Including an input prompt:
>>> input('Line: ')[::-1]
Line: this is my stuff
'ffuts ym si siht'
There are several ways to make Python speak backwards, and all of them work, and I hope they help you.
Here are some solutions that Grok Learning itself recommends:
text = input('Line: ')
last_index = len(text) - 1
backwards_text = ''
for i in range(last_index, -1, -1):
backwards_text = backwards_text + text[i]
print(backwards_text)
line = input('Line: ')
for i in range(len(line)-1, -1, -1):
print(line[i], end='')
print()
These both work, and they both use a slight different way on how to print backwards, but they both use a for
loop, and I hope both of these help you, and I hope you find this helpful.
y = input("Line: ")
print(y[::-1])
works like a beauty
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.