How do I remove the whitespace from the first iteration of my for loop?

Viewed 77

Code:

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range(triangle_height):
    updatedChar = ' '.join([triangle_char]*i) 
    print(triangle_char + ' ' + updatedChar + ' ')
    i += 1

The output is correct but I can't seem to get rid of the extra " " whitespace at the end of the first iteration.

Example Output:

% # How to remove this whitespace but keep the others
% %
% % %
2 Answers

Multiple updatedChar by i + 1 and print it without appending the sign again. You can also remove the i += 1, it has no effect

for i in range(triangle_height):
    updated_char = ' '.join(triangle_char * (i + 1))
    print(updated_char)

Output

%
% %
% % %

strip() should do what you want

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height+1):
    updatedChar = ' '.join([triangle_char]*i)
    print((triangle_char + ' ' + updatedChar + ' ').strip())
    i += 1
Related