w3resource

Python: Display a number in left, right and center aligned of width 10


Align number left, right, center (width=10).

Write a Python program to display a number in left, right, and center aligned with a width of 10.

Python String Exercises: Display a number in left, right and center aligned of width 10

Sample Solution:

Python Code:

# Define a variable 'x' and assign it the value 22 (an integer).
x = 22

# Print an empty line for spacing.
print()

# Print the original value of 'x' with a label.
print("Original Number: ", x)

# Format and print the value of 'x' with left alignment, a width of 10 characters, and padding using spaces.
print("Left aligned (width 10)   :"+"{:< 10d}".format(x))

# Format and print the value of 'x' with right alignment, a width of 10 characters, and padding using spaces.
print("Right aligned (width 10)  :"+"{:10d}".format(x))

# Format and print the value of 'x' with center alignment, a width of 10 characters, and padding using spaces.
print("Center aligned (width 10) :"+"{:^10d}".format(x))

# Print an empty line for spacing.
print()

Sample Output:

Original Number:  22                                                                                          
Left aligned (width 10)   :22                                                                                 
Right aligned (width 10)  :        22                                                                         
Center aligned (width 10) :    22  

Flowchart:

Flowchart: Display a number in left, right and center aligned of width 10

For more Practice: Solve these Related Problems:

  • Write a Python program to display a number left-aligned, right-aligned, and center-aligned within a 10-character field.
  • Write a Python program to use f-string formatting to align a number in a field of width 10 in different ways.
  • Write a Python program to print a number in left, right, and center alignments using the format() method with appropriate specifiers.
  • Write a Python program to demonstrate number alignment in a 10-character field by printing the same number in three different alignments.

Go to:


Previous: Write a Python program to format a number with a percentage.
Next: Write a Python program to count occurrences of a substring in a string.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.