In this tutorial, we’ll learn what Python string ljust() method is and how to properly use it. We’ll go through multiple Python code examples to understand how ljust() method works in Python.
Outline
- Introduction: Python String ljust() Method
- Syntax of ljust() Method
- Example 1: Python String ljust() Method Applied on a String
- Example 2: ljust() Method in Python For Loop
- Example 3: Python String ljust() Method Return Value
- Conclusion
Introduction: Python String ljust() Method
This method is used to return a left justified Python string with a specified minimum width.
Syntax of ljust() Method
string.ljust(width,char(optional))
- Python string ljust() method take two arguments.
- First one specifies the width of the new returned string. If the width is less than or equal to the original string then only the string will be returned.
- Second argument is optional. Its used to fill the remaining string with a character specified in it. Whitespace character will be used if no character is passed to it.
Example 1: Python String ljust() Method Applied on a String
val='Python' print(val.ljust(10,'*')) print('Python'.ljust(10)) // whitespace applied if no character is specified print('Python'.ljust(7,'*')) print('Python'.ljust(5,'*')) print('Python'.ljust(15,'-'))
Output
Python**** Python // white spaces are applied to it Python* Python Python---------
This is how Python string ljust method works. We can see that by providing a width of equal or less than the actual length of string will result in just the original string returned by this method. Also, whitespaces will be applied by default if no other character is specified.
Example 2: ljust() Method in Python For Loop
val='Python Program' for var in range(13,20): print(val.ljust(var,'-'))
Output
Python Program Python Program Python Program- Python Program-- Python Program--- Python Program---- Python Program-----
We’ve created a simple example program to demonstrate how Python string ljust method can be used in Python for loop. You can customize it according to your set of requirements.
Example 3: Python String ljust() Method Return Value
val= 'Python Program' returnedValue= val.ljust( 18, '=' ) print( returnedValue ) print( val ) // original string
Output
Python Program==== Python Program // original string
Python string ljust method does not modify the existing string. It returns a new modified string.
Conclusion
To conclude this tutorial, I hope you now have a detailed practical understanding of how to properly use Python string ljust method. I’ll be looking forward to receive your feedback on this post. Thank you for reading it.
You may like to read:
How To Use Python String IsUpper Method – Easy Python Example Code
How To Use Python String IsSpace Method – Easy Python Example Code
How To Use Python String IsLower() Method – Easy Python Code Examples
How To Use Python String IsTitle Method – Easy Python Example Code
How To Use Python String IsNumeric Method – Easy Python Code Examples