Tech Wz
Tech Wz

Reputation: 11

Python, Slicing a string at intervals while keeping the spaces?

I need to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.

So it should look like this

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

or

Message? pbaynatnahproarnsm
p y t h o n

I've tried this:

nim = input("Line: ")[::+3]

and it works fine, but I have to keep the spaces between the letters.

Upvotes: 1

Views: 439

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195543

If you want to just print the letters out of sentence with spaces between them, you can use sep= parameter of print() and asterisk *:

print(*input("Line: ")[::3], sep=' ')

Prints:

Line: cxohawalkldflghemwnsegfaeap
c h a l l e n g e

Upvotes: 0

Chris
Chris

Reputation: 29742

Use str.join:

nim = '  '.join(input("Line: ")[::3])
# Line: pbaynatnahproarnsm
print(nim)

Output:

'p  y  t  h  o  n'

Upvotes: 2

Related Questions