Python is a versatile programming language that can be used for many different applications. One of the most commonly sought after formatting tasks is how to right align strings. Right aligning a string allows you to easily compare strings of different lengths and helps make code more readable. This article outlines how to right align a string in Python 3.
There are two main ways to right align strings in Python: using the str.rjust() method, and using formatting strings. These methods are simple and effective ways to format a string in order to make it easy to compare two strings of different lengths.
Using the str.rjust() Method
The str.rjust() method takes two arguments: the content of the string being formatted, and an integer denoting the desired length of the outputted string (plus any additional spaces). The syntax looks like this:sh string_content = "Hello world!" print(string_content . rjust(20)) # prints out " Hello world!"
In this example, we have stored our content into a variable called string_content and then printed it out on one line with 20 characters of space before it due to us passing an integer argument of 20 into our rjust() method call. Note that only if after formatting our desired output includes more than 20 characters due to having multiple words, will text wrap around onto additional lines begin pasted on in order from left-to-right from top-to-bottom; as shown here with “Hello World! This is unwrapped text”.
String Alignment in Python
Aligning strings can be a useful way to create a more attractive output in your Python program. It is also useful for creating well structured tables that contain data. In this article, we will discuss the various ways to align strings in Python and how to implement them.
Using the rjust() Method
The rjust() method is used to right-align the strings in a given string. This method takes one argument, width—the total field width of the string. The field width is basically the total length of characters that you would like the string to contain. If the length of the given string is less than this width then it pads it with specified character from its left side.
By default, Python uses white space (blank) as padding whenever we use this method to align characters in a string. However, if you wish you can use another character for padding instead of blank spaces too.
Let’s understand better with an example –text = "Hello World!"
Using the rjust()
method with its default padding character, whitespace:text = text.rjust(20)
#here we are setting width = 20 and since text size = 12 so 8 spaces will be added at left side
print(text) # Output: “ Hello World!” (eight whitespaces are added before “Hello World!” to make total size 20 )
Let’s look into another example where we will try and add zeroes as a padding character to align our given string: text_2 = "Cat"
text_2 = text_2.rjust(5, '0')
# here width=5 and since text size > 5 so no space needed but padding will be added using ‘0’ as a charcter print(text_2) # Output: ”00Cat” (three zeroes are added before “Cat” to make total size 5 )
Using the format() Method
Using the format() method, we can right-align string in Python within the specified width of a string. The syntax used for this is:
format(string,width).
In this syntax:
-The ‘string’ refers to the specific string meant for alignment.
-The ‘width’ refers to the maximum length of the aligned string. Any character that is beyond this length will be discarded.
In order to print a right-aligned string using Python, follow these simple steps:
- First, declare a variable and store your desired string in it. For example: myStr = “Hello There!”;
- Now, let’s right-align it with a width of 15 characters by using the format() method as: result = format(myStr, ‘>15’); Here, “>” indicates that text should be right aligned with respect to 15 character width defined in second parameter followed by an integer (15). If you want to left align or center align your text then use “<” or “^” instead of “>”.
- Finally print the resultant string using a print statement as shown below: print(result) When you execute this program in Python shell then you will get following result − Output: Hello There!Using the format() Method with Strings
The basic syntax for using the format() method is as follows: string.format(value1,value2,…). This method is used to replace parts of a string with values from a list of parameters.
It can also be used for left aligning other data types such as integers, floats or Boolean values. Let’s take a look at how we would go about right aligning strings in Python using the format() method.
Using the ‘>’ operator in the format() method allows us to right align strings in Python by providing an integer which determines the number of spaces between a defined pattern and its content. Other than controlling the alignment, it also enables us to control the width of a field by setting it manually or dynamically depending on our needs.
For example, let’s say we want to make sure that all our player aliases have the same width for easy readability and comparison purposes. We can easily do this by specifying a fixed-width when assigning their values:
player_one = “Jack”
player_two = “Anna”
print(“{: >6}”.format(player_one)) # Outputs => ” Jack”
print(“{: >6}”.format(player_two)) # Outputs => ” Anna”
We can also use the * operator (instead of an integer) which enables us to dynamically assign width so that its value adjusts according to our iterable length: scores= [90, 85, 78]
print(“{: >*}”.format(max(scores))) # Outputs => ” 90″
Conclusion
To conclude, right alignment of strings in Python can be done in three ways depending upon the output that require one to achieve. The first approach is to use the “%-widths” expression, namely %-20s, whereby the figures indicate how many characters of text should be inputted. The second approach is by making use of the string’s rjust method which takes two arguments; one for the string width and other for a character that should be padded on the left side. Finally, format function with parameter as “>n” is a third way presenting an easy yet powerful alternative for text alignment.