How To Do Print Formatting In Python With Chunks Of Strings?
I'm having some trouble with formatting the pyramid. I've tried to use format when printing from the loop but that didn't seem to work and just breaks the program. What would be di
Solution 1:
The things to consider for this problem are
- The length of the largest number.
- The length of the current number being printed.
- The difference in lengths.
In order to correctly space everything, you're going to need to print extra spaces after the numbers with less digits (to compensate for the extra digits in the larger number).
For example, if you have a row that contains the number 10, in order to correctly space the other smaller numbers, you're going to need to use extra spaces to compensate for that second digit in the number 10.
This solution works for me.
userinput = int(input("Enter the number of lines: " ))
userinput = userinput + 1# Here, you can see I am storing the length of the largest number
input_length = len(str(userinput))
for i inrange(1, userinput):
# First the row is positioned as needed with the correct number of spaces
spaces = " " * input_length
for j inrange(userinput - i):
print(spaces, end = " ")
for j inrange(i, 0, -1):
# Now, the current numbers length is compared to the # largest number's length, and the appropriate number# of spaces are appended after the number.
spaces = " " * (input_length + 1 - len(str(j)))
print(j, end = spaces)
for j inrange(2,i + 1):
# The same is done here as in the previous loop.
spaces = " " * (input_length + 1 - len(str(j)))
print(j, end = spaces)
print()
j += 1
Solution 2:
Take a look at https://stackoverflow.com/a/13077777/6510412
I think this might be what you're looking for. I hope it helps.
Post a Comment for "How To Do Print Formatting In Python With Chunks Of Strings?"