svnrod
svnrod

Reputation: 31

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

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
% %
% % %

Upvotes: 2

Views: 172

Answers (2)

Guy
Guy

Reputation: 50809

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

%
% %
% % %

Upvotes: 2

Abdul Mohsi
Abdul Mohsi

Reputation: 13

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

Upvotes: 0

Related Questions