Home > OS >  python: how to add space before words using an end=''
python: how to add space before words using an end=''

Time:10-03

I want to output:

  0 1 2 3

with 2 spaces before 0 and 1 space between each of the numbers.

I wrote the following statement:

print('  ' str(j),end=' ')

Where j increases from 0 until it reaches the input. However, the output ends up having 2 space before 0 and 3 spaces between each of the numbers.

How can I modify my code?

CodePudding user response:

i think it shouldn't be placing 2 spaces before 0. Perhaps you accidentally put 2 spaces in your quotations. As to how to do what you need this to do... Perhaps try an if statement: if 'number' == 0 print(' ') after that you just put print (str(j), end=' ') tell me if it works or not

CodePudding user response:

You have to use .join method of a list and string addition in a print

numbers = [1, 2, 3, 4]
print(" " * 3   " ".join([str(number) for number in numbers]))

CodePudding user response:

If all you want is to print this string, then you can generate it with join and list comprehension:

print('  '   ' '.join([str(i) for i in range(4)]))

If this is part of a for loop, then just check and print two spaces whenever you're in the first iteration:

for i in range(4):
    if i == 0:
        print('  ', end='')  # add the 2 space before the first 0
    print(f'{i} ', end='')   # the space in behind number is preemptively added

    # your other code...
  • Related