Python String ljust() – ItsMyCode

0
49
Python String ljust() - ItsMyCode


The string ljust() method is a built-in function that will left align the string using a specified character as the fill character. The default character is space if no argument is passed.

ljust() Syntax

The syntax of ljust() method is:

string.ljust(width[, fillchar])

The fillchar is an optional parameter.

ljust() Parameters

The ljust() method can take two parameters:

  • width – length of the string with fill characters. 
  • fillchar (Optional) – A character to fill the missing space (to the right of the string). Default is space.

 ljust() Return value

The ljust() method returns the left-justified string using a specified fill character and given minimum width.

The original string is returned as-is if the width is less than or equal to len(s)

Example 1 : Python program to left justify a string

In the below program, the string “ItsMyCode” will be left-justified. Since the width provided is 12 and the original string is 9 characters, the ljust() method will add the default fill char(space) padding to the right to make it 12 characters.

text = "ItsMyCode"
width = 12

print("Length of original string:", len(text))

# Default space is taken for padding
output = text.ljust(width)
print(output)
print("Length of left aligned string:", len(output))

Output

Length of original string: 9
ItsMyCode   
Length of left aligned string: 12

Example 2: ljust() Method With * fillchar

The string “Python” will be left-justified and * is used as a fill char on the right side of the string.

text = "Python"
width = 12

print("Length of original string:", len(text))

# fill char * is taken for padding
output = text.ljust(width, "*")
print(output)
print("Length of left aligned string:", len(output))

Output

Length of original string: 6
Python******
Length of left aligned string: 12

Example 3: Returns original string if the width is less than length of string

In this example the width specified is 10 and the length of the string is 16. Hence the ljust() method returns the original string as-is without any padding characters.

text = "Python Tutorials"
width = 10

print("Length of original string:", len(text))

# returns original string as-is
output = text.ljust(width, "*")
print(output)
print("Length of left aligned string:", len(output))

Output

Length of original string: 16
Python Tutorials
Length of left aligned string: 16



Source link

Leave a reply

Please enter your comment!
Please enter your name here