简体   繁体   中英

Remove trailing white space in python 3

Having bit of trouble with a program i made. i am getting it to display a diamond but i have a problem, here is my code:

a = input("Enter width: ")
a = int(a)
b = a
for i in range(a):
  i = i + 1
  b = a - i
  text = " " * b + " " + "* " * i
  print(text[:-1])
for i in range(a):
  i = i + 1
  b = a - i
  text = " " * i + " " + "* " * b
  print(text[:-1])

Thanks for all the help! this is the answer

That's because print doesn't return the string, it returns None .

>>> print(print("foo"))
foo
None

Perhaps you wanted to do this:

text = " " * i + " " + "* " * b
print (text[:-1])

To remove the trailing white-space better use str.rstrip :

>>> "foo ".rstrip()
'foo'

help on str.rstrip :

>>> print (str.rstrip.__doc__)
S.rstrip([chars]) -> str

Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.

You can write your slice like this (not on the print return value):

("* "*b)[:-1]

or, you can use join:

' '.join(['*']*b)

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