String Formatting - PYTHON Alignment

Asked

Viewed 408 times

0

my question is, instead of :>6, I wanted the user to be able to choose the amount of characters to be aligned to the right, for example, there instead of 6, I would put the variable n.

However, python accuses an error, implying that it only accepts numbers that are directly placed there as a parameter, I cannot play the variable n that is already int by the way. There’s some way to do it?

def staircase(n):
        grade = "#"
        vezes = 1
        for i in range(0, n):
            print(f"{grade:>6}")
            vezes += 1
            grade = "#" * vezes
    if __name__ == '__main__':
        n = int(input())
    
        staircase(n)

1 answer

2


Just put the variable also between keys:

print(f"{grade:>{n}}")

Thus the value of the variable n will be interpolated in the string and will still be considered as a parameter of formatting the value of grade.

More information, see PEP 498

  • Grateful Woss, I didn’t know about this interpolation.

  • 2

    gee - I didn’t know this - even before I saw it here, I thought it had to be in 2 steps - first create a string with the formatting parameters, and then format again to include the parameters: print(f"{{grid: >{n}}}". format(grid=grid) )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.