Use the rjust()
to right-justify a string.
word = 'beach'
number_spaces = 32
word_justified = word.rjust(number_spaces)
print(word)
#'beach'
print(word_justified)
#' beach'
Notice the spaces in the second string. The word ‘beach’ has 5 characters, which gives us 27 spaces to fill with empty space.
The original word
variable remains unchanged, thus we need to assign the return of the method to a new variable, word_justified
in this case.
The rjust()
also accepts a specific char as a parameter to fill the remaining space.
word = 'beach'
number_chars = 32
char = '$'
word_justified = word.rjust(number_chars, char)
print(word)
#beach
print(word_justified)
#$$$$$$$$$$$$$$$$$$$$$$$$$$$beach
Similar to the first situation, I have 27 $
signs to make it 32 total when I count the 5 chars contained in the word ‘beach’.