0

so i have to create a code in which it reads every third letter and it creates a space in between each letter, my code creates the spaces but it also has a space after the last letter, this is my code:

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

My output was:

Message?

I enter:

 cxohawalkldflghemwnsegfaeap

I get back

c h a l l e n g e 

when the output isn't meant to have the last " " after the e.

I have read by adding print(" ".join(x)) should give me the output i need but when i put it in it just gives me a error. Please and Thank you

2
  • Can you show us the second version that used join but failed? join requires a list or sequence and you likely didn't build the list first. Commented Mar 6, 2016 at 5:44
  • 1
    Use the title to describe the specific problem. The current title has little information. Commented Mar 6, 2016 at 5:47

2 Answers 2

7

In Python, strings are one kind of data structures called sequences. Sequences support slicing, which is a simple and fancy way of doing things like "from nth", "to nth" and "every nth". The syntax is sequence[from_index:to_index:stride]. One does not even a for loop for doing that.ago

We can get every 3th character easily by omitting from_index and to_index, and have stride of 3:

>>> msg = input("Message? ")
cxohawalkldflghemwnsegfaeap
>>> every_3th = msg[::3]
>>> every_3th
'challenge'

Now, we just need to insert spaces after each letter. separator.join(iterable) will join elements from iterable together in order with the given separator in between. A string is an iterable, whose elements are the individiual characters.

Thus we can do:

>>> answer = ' '.join(every_3th)
>>> answer
'c h a l l e n g e'

For the final code we can omit intermediate variables and have still a quite readable two-liner:

>>> msg = input('Message? ')
>>> print(' '.join(msg[::3]))
Sign up to request clarification or add additional context in comments.

Comments

1

Try

>>> print " ".join([msg[i] for i in range(0, len(msg), 3)])
'c h a l l e n g e'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.