Python String ljust() Method
The ljust() function returns a new copy of the original string with the fill characters that are passed in the 'character' argument from the right. If no character is passed in the 'character' argument, blank white spaces will be added. With a number passed to the length argument to specify the total number of characters for the string
How to formulate it like this:
string. adjust(length, character)
character: [Optional] A character or group of characters is passed to fill in the blanks. If no character is passed, blank spaces will be added by default.
length: A number is passed to specify the total number of characters for the string. If the number passed to this argument is less than or equal to the length of the original string, the original string is returned.
Return value: Returns a new string of a given length and adds certain characters to the right side of the original string.
In the following example, we will not pass any characters or symbols to the "character" argument. By default, the blanks on the right will be filled with white space. With "15" passed to the length argument to specify the total number of characters for the string
first_name = "ahmed"
last_name = "obaid"
print(first_name.ljust(15), last_name)
The output will be:
ahmed obaid
Example:
string = "ahmed obaid"
a = string.ljust(20)
print(a, "this is my name.")
The output will be:
ahmed obaid this is my name.
In the following example, we will pass the $ character to the "character" argument to fill in the blanks from the right. Passing "18" to the length argument to specify the total number of characters for the string
Example:
string = "ahmed obaid"
print(string.ljust(18, '$'))
The output will be:
ahmed obaid$$$$$$$
In the following example, we will pass the underscore "_" to the "character" argument to fill in the blanks on the right. Passing "10" to the length argument to specify the total number of characters for the string
Example:
string = "ahmed"
print(string.ljust(10, '-'))
The output will be:
ahmed-----
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python Python String string methods python python string ljust method
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment