简体   繁体   中英

How to print a string in each line with some space from the first of the line?

I did not write a clear subject because I didn't know what to write about it, sorry first of all.

What I want to reach is:

a
    a
        a
            a
                a
            a
        a
    a
a

With for loop I think I can reach this, but what I try is totally wrong.

Your increment counter is useless in your code.

The way I would approach this is:

column_num = 0
for i in range(10):  # rows
    for j in range(10):  # cols
        if j == column_num:
            print("a", end='')
        else:
            print(' ', end='')
    print()  # newline
    column_num += 1

#then reverse:
column_num -= 1
for i in range(10): #rows
    for j in range(10): #cols
        if j == column_num:
            print("a", end = '')
        else:
            print(' ', end = '')
    print() #newline
    column_num -= 1

Maybe you are locking for something like this.

a = 'a    '
space = '\t'

for c in range(5):
    print(space*c + a)

for c in range(5,0,-1):
    print(space*c + a)

You can do it recursively:

def print_angle(s, start, end, direction):
    indent = "  "*start
    print(f"{indent}{s}")

    if start < end-1 and direction:
        print_angle(s, start+1, end, 1)
    elif start > 0:
        print_angle(s, start-1, end, 0)

print_angle('a', 0, 5, 1)

This prints:

a
   a
      a
        a
           a
        a
      a
   a
a

The idea here is:

1. Pass the desired character to print - a in this case.

2. Pass the starting point - 0 indents in this case.

3. Pass the ending point - 5 total to go.

4. Pass direction in which to go - 1 up, 0 down.

5. Go recursively up until you reach the end, preserve direction, initially up.

6. Go recursively down until you reach 0 and exit.

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