Reference Materials
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python String Methods
- Python String capitalize()
- Python String center()
- Python String casefold()
- Python String count()
- Python String endswith()
- Python String expandtabs()
- Python String encode()
- Python String find()
- Python String format()
- Python String index()
- Python String isalnum()
- Python String isalpha()
- Python String isdecimal()
- Python String isdigit()
- Python String isidentifier()
- Python String islower()
- Python String isnumeric()
- Python String isprintable()
- Python String isspace()
- Python String istitle()
- Python String isupper()
- Python String join()
- Python String ljust()
- Python String rjust()
- Python String lower()
- Python String upper()
- Python String swapcase()
- Python String lstrip()
- Python String rstrip()
- Python String strip()
- Python String partition()
- Python String maketrans()
- Python String rpartition()
- Python String translate()
- Python String replace()
- Python String rfind()
- Python String rindex()
- Python String split()
- Python String rsplit()
- Python String splitlines()
- Python String startswith()
- Python String title()
- Python String zfill()
- Python String format_map()
Python String ljust()
The syntax of ljust() method is:
string.ljust(width[, fillchar])
Here, fillchar is an optional parameter.
String ljust() Parameters
ljust() method takes two parameters:
- width - width of the given string. If width is less than or equal to the length of the string, the original string is returned.
- fillchar (Optional) - character to fill the remaining space of the width
Return value from String ljust()
The ljust() method returns the left-justified string within the given minimum width.
If fillchar is defined, it also fills the remaining space with the defined character.
Example 1: Left justify string of minimum width
# example string
string = 'cat'
width = 5
# print left justified string
print(string.ljust(width))
Output
cat
Here, the minimum width defined is 5. So, the resultant string is of minimum length 5.
And, the string cat is aligned to the left which makes leaves two spaces on the right of the word.
Example 2: Left justify string and fill the remaining spaces
# example string
string = 'cat'
width = 5
fillchar = '*'
# print left justified string
print(string.ljust(width, fillchar))
Output
cat**
Here, the string cat is aligned to the left, and the remaining two spaces on the right is filled with the character *.
Note: If you want to right justify the string, use rjust(). You can also use format() method for the formatting of strings.
