简体   繁体   中英

Python - White Spaces

I've made a program as follows:

x = input('Message? ')
x = x[::3]
for i in x:
  print(i, end=' ')

it's supposed to give me the letters of input (every third letter) which it does, although it also prints a white space at the end which I have been unable to get rid of. I've tried everything including the .rstrip and [:-1] with no luck

You are telling print() to print that whitespace with end=' ' .

Instead of calling print() repeatedly, pass in the whole list in one go:

print(*x)

Now each element of x is printed as a separate argument , using the default 1-space separator, and a newline as end .

Outside of passing in the elements as separate arguments to print() , you can also use str.join() to build one string with separators; this does require that all elements in x are strings or you'd need to explicitly convert them:

print(' '.join(x))

Try this:

x = input('Message? ')
x = x[::3]
print(' '.join(x[::3]))

join lets you put a space between adjacent characters, leaving out the trailing white-space

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