简体   繁体   English

grok 学习:python 课程,向后打印

[英]grok learning: python course, printing backwards

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: grok学习python课程的一个问题是,“编写一个程序,读入一行文本,然后向后打印出该行文本。”我写道:

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.我要做的是将单词的反向存储在另一个变量new_word ,然后在 for 循环之后打印它。

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.有几种方法可以让 Python 逆向说话,它们都可以工作,希望对你有所帮助。

Here are some solutions that Grok Learning itself recommends:以下是 Grok Learning 本身推荐的一些解决方案:

  • Sample solution #1:示例解决方案 #1:
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)
  • Sample solution #2:示例解决方案 #2:
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.这两个都有效,而且它们在如何向后打印方面使用的方式略有不同,但是它们都使用for循环,我希望这两个都可以帮助你,我希望你觉得这有帮助。

y = input("Line: ")

print(y[::-1])

works like a beauty像美女一样工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM