Remember
ljust() pads on the right so text is left-aligned in a minimum width. It returns a new string.
ljust() pads on the right so text is left-aligned in a minimum width. It returns a new string.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'tea'
result = text.ljust(8, ".")
print(result)Top-level scope
'tea'Object 2 · str'tea.....'ljust() pads on the right so text is left-aligned in a minimum width. It returns a new string.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'tea'
result = text.ljust(8, ".")
print(result)
|
v
DISPLAYED RESULT
tea.....
FINAL BINDINGS
text --> object 1 (str)
result --> object 2 (str)
object 1: 'tea'
object 2: 'tea.....'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'tea'
result = text.ljust(8, ".")
print(result)Top-level scope
'tea'Object 2 · str'tea.....'The example has finished. Compare the final output with the values and references above.
tea.....
What do you expect this program to print?
text = 'tea'
result = text.ljust(8, ".")
print(result)ljust() MethodThe ljust() method in Python left-aligns a string by padding it with spaces (or a specified character) until it reaches the desired width.
string.ljust(width, fillchar=' ')
width – Total length of the resulting string (including the original string and padding)fillchar (optional) – The character to use for padding. Default is a space ' 'text = "Hello"
print(text.ljust(10))
Hello
Explanation: The word "Hello" is padded with 5 spaces on the right to make the total length 10.
text = "Hi"
print(text.ljust(6, '-'))
Hi----
Explanation: The string "Hi" is padded with 4 hyphens '-' on the right.
fillchar must be a single character. Using more than one character will raise an error.width is less than or equal to the string's length, the original string is returned unchanged.Use ljust() in string formatting questions where consistent alignment of text output is required.
ljust() pads the string on the right to make it left-aligned.Write a Python program that prints a list of names left-aligned within 15 characters using ljust().
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name.ljust(15) + "|")
Alice |
Bob |
Charlie |
Connect what you noticed in the example with the idea below.
ljust() pads on the right so text is left-aligned in a minimum width. It returns a new string.
ljust() pads on the left.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.