Reputation: 45
The goal of this code is to take a bunch of letters and print the first letter and every third letter after that for the user. What's the easiest way to remove the whitespace at the end of the output here while keeping all the spaces in the middle?
msg = input('Message? ')
for i in range(0, len(msg), 3):
print(msg[i], end = ' ')
Upvotes: 0
Views: 2397
Reputation: 131
n = ' hello '
n.rstrip()
' hello'
n.lstrip()
'hello '
n.strip()
'hello'
Upvotes: 1
Reputation: 6526
You can use at least 2 methods:
1) Slicing method:
print(" ".join(msg[0::3]))
2) List comprehension (more readable/powerful):
print(" ".join([letter for i,letter in enumerate(msg) if i%3==0])
Upvotes: 0
Reputation: 2120
What about?
msg = input('Message? ')
output = ' '.join(msg[::3]).rstrip()
print(output)
Upvotes: 0
Reputation: 46563
str_object.rstrip()
will return a copy of str_object
without trailing whitespace. Just do
msg = input('Message? ').rstrip()
For what it's worth, you can replace your loop by string slicing:
print(*msg[::3], sep=' ')
Upvotes: 2