4

I have to print out every third letter of a text with spaces between and none at the end. I can do everything but the spaces between each of the letters.

Here is what I have.

line = input('Message? ')                                          
print(line[0]+line[3::3].strip())

2 Answers 2

7

To join things with spaces, use join(). Consider the following:

>>> line = '0123456789'
>>> ' '.join(line[::3])
'0 3 6 9'
Sign up to request clarification or add additional context in comments.

Comments

-2

Since you're using Python 3, you can use * to unpack the line and send each element as an argument to print(), which uses a space as the default separator between arguments. You don't need to separate line[0] from the rest - you can include it in the slice ([0::3]), or it'll be used by default ([::3]). Also, there's no need to use strip(), as the newline character that you send with Enter is not included in the string when you use input().

print(*input('Message? ')[::3])

7 Comments

Thnx, i think i was looking for something that would be more complex and in doing so forgot to think about any simpler options
This will print the required output very tidily, providing a good example of Python 3's print() function with a clear explanation. Why the downvote?
How to use the separated arguments ?
@zetysz - They already are used. They are unpacked and sent to print(), which prints them with a space separator as the question specifies.
I want a list as a result if possible .[1, 2, 3]
|

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.