简体   繁体   中英

Python f-string with variable width alignment

I want to print below code.

!!!!** !!!**** !!****** !********

So I use while loop with i, j. But, in some parts, the output of. becomes weird, I tried some case, there is no problem if the i and j are in ascending order. but there is a problem if they are in descending order, Below my code, print(i. j) means there was no problem with the value of i and j.

i = 0
j = 6
s1 = ""
s2 = ""
while True:
    i += 1
    j -= 1
    if i > 5: break
    s1 = f"{s1:!<{j}}"
    s2 = f"{s2:*^{i*2}}"
    print(i, j)
    print(s1+s2)
1 5
!!!!!**
2 4
!!!!!****
3 3
!!!!!******
4 2
!!!!!********
5 1
!!!!!**********

Aren't you over-complicating things a bit here? If it's the pattern you are looking for here:

def print_pattern(bangs: int, stars: int)->None:
    output = f"{'!'*bangs}{'*'*stars}"
    print(output)

Care to provide some more explanations about what do you expect actually? Is the total number of chars fixed? Is it the sum of i and j, something else?

i, j = 0, 6
total = i+1
while i+j == total:
    if i>5:
        break
    print_pattern(bangs=i, stars=j)
    i+=1
    j-=1

Use only 1 print, and include 'end' with a space:

print(...., end = " ")

i = 0
j = 6
s1 = ""
s2 = ""
while True:
    i += 1
    j -= 1
    if i >= 5:
        break
    s1 = f"{'!'*(j-1)}"
    s2 = f"{s2:*^{i*2}}"
    print(s1 + s2, end=" ")

Output:

!!!!** !!!**** !!****** !******** 

I also modified your break clause.

It looks like you want a space after each sequence of asterisks but probably not at the end of the output. Therefore:

M = 4
N = 2

for m in range(M, 0, -1):
    print(f"{'!' * m}{'*' * N} ", end='')
    N += 2

print('\b')

Output:

!!!!** !!!**** !!****** !********

I found wrong thing.

s1 = f"{s1:!<{j}}" in this part, value(j) is max value.

So, s1 already full. At the end of the loop, s1 must be initialized.

I should add s1 = ""

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