简体   繁体   中英

how to get rid of the whitespace at the end?

i'm just a beginner to python and i have been asked to solve a problem where your program has to decode a code in which it takes every 3rd letter and puts them together with a gap in between each letter, sorry that was a bad explanation but have a look at my code:

    m=input("Message? ")
    for c in m[::3]:
      print(c,end=' ')

the problem is there's a whitespace after the last letter and i dont know how to get rid of it, i've tried.rstrip and that doesnt work. i've also tried to [::-1]after the end=' ' and that doesn't work.

You could use str.join on a list comprehension rather than a loop:

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

This would put a space between each letter, excluding the trails.

I'm not sure what the problem is exactly but I'm assuming you mean to say that on your last print you do not want the end=' ' whitespace. To produce the string you want you can join the slice on whitespace as lltt said, minus the redundant list comprehension.

m = "123456789"
print(" ".join(m[::3]))

Output:

"1 4 7"

If you really want to maintain your for loop print functionality you need a way to determine if you are in the last loop. This is a general problem which has various solutions such as a look-ahead function. But you can simply break up the for loop into two parts.

m="123456789"
for c in m[::3][:-1]:
    print(c,end=' ')
print(m[::3][-1], end='')

Output:

1 4 7

Of course you do not need the end='' in the last print; print(m[::3][-1]) is fine. It is just there for readability.

If you mean to say that the decoded message cannot have a whitespace as the last character then you can use.rstrip(). For example when the last, third character of the input, is a whitespace.

m = "input with trailing whitespace "
print(" ".join(m[::3]))

Output:

"i u w h r l g h e a  "

Here you can chain the rstrip() method.

m = "input with trailing whitespace "
print(" ".join(m[::3]).rstrip())

Output:

"i u w h r l g h e a"

When working with strings, you should avoid hand-crafted solutions that are inefficient and often incorrect. Connect the letters with spaces using the string method .join() :

m = "Hello, world!"
print(" ".join(m[::3]))
#'H l w l'

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