[英]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 我尝试了包括.rstrip
和[:-1]
在内的所有操作,但没有.rstrip
运气
You are telling print()
to print that whitespace with end=' '
. 您正在告诉print()
使用end=' '
打印该空格。
Instead of calling print()
repeatedly, pass in the whole list in one go: 与其重复调用print()
,不如一次传递整个列表:
print(*x)
Now each element of x
is printed as a separate argument , using the default 1-space separator, and a newline as end
. 现在,使用默认的1空格分隔符和换行符作为end
,将x
每个元素打印为单独的参数 。
Outside of passing in the elements as separate arguments to print()
, you can also use str.join()
to build one string with separators; 除了将元素作为单独的参数传递给print()
,还可以使用str.join()
来构建一个带分隔符的字符串; this does require that all elements in x
are strings or you'd need to explicitly convert them: 这确实要求x
中的所有元素都是字符串,或者您需要显式转换它们:
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 join
使您可以在相邻字符之间放置一个空格,而在结尾处留空白
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.