简体   繁体   中英

Printing Out Every Third Letter Python

I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.' This is my code:

text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
 decoded = text[i]
 print(decoded, end=" ")

Although I it says it isn't correct, it say this is the desired out-put:

Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e

And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?

要仅字符之间留有空格,您可以使用切片创建字符串"challenge"然后使用str.join添加空格:

" ".join(text[::3])

Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"

So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:

line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
  result += ' ' + line[i]
print(result)

Or this:

line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
  print(' ' + line[i], end='')
print()

Or maybe this:

code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])

All of these should work, and I hope this answers your question.

I think Grok is just really picky about the details. (It's also case sensitive) Maybe try this for an alternative because this one worked for me:

message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
  decoded += message[i] + ' '
print(decoded.rstrip())

You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.

Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.

output = ""
for i in range(10):
  output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())

If you look through the Grok course, there is one page called 'Step by step, side by side' (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/ ) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.

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.

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