📅  最后修改于: 2023-12-03 14:46:04.938000             🧑  作者: Mango
Python text formatting is an essential skill needed in programming as it enables you to format and print output strings in a readable and organized manner. In this article, we will explore how to format rows in Python using different techniques.
ljust()
, rjust()
, and center()
MethodsOne way to format rows in Python is by using the ljust()
, rjust()
, and center()
methods. These methods are available for all string objects and offer a convenient way to pad strings with spaces.
The ljust()
method left-aligns the string and pads it with spaces on the right. The rjust()
method does the opposite and right-aligns the string, padding it with spaces on the left. The center()
method centers the string and pads it with spaces on both sides.
# Example
name = "John"
age = "35"
job = "Developer"
print(name.ljust(10) + age.ljust(10) + job.ljust(10))
print(name.rjust(10) + age.rjust(10) + job.rjust(10))
print(name.center(10) + age.center(10) + job.center(10))
This code will output:
John 35 Developer
John 35Developer
John 35 Developer
format()
MethodAnother way to format rows in Python is by using the format()
method. This method provides a flexible way of formatting strings and can be used to align strings, insert variables, and format numbers.
# Example
name = "John"
age = "35"
job = "Developer"
print("{:<10}{:<10}{:<10}".format(name, age, job))
print("{:^10}{:^10}{:^10}".format(name, age, job))
print("{:>10}{:>10}{:>10}".format(name, age, job))
This code will output:
John 35 Developer
John 35 Developer
John 35Developer
%
OperatorThe %
operator is an older way of formatting strings in Python. It can be used to format strings in a similar way as the format()
method. However, it is less flexible and requires more code.
# Example
name = "John"
age = "35"
job = "Developer"
print("%-10s%-10s%-10s" % (name, age, job))
print("%10s%10s%10s" % (name, age, job))
print("%*s%*s%*s" % (-10, name, -10, age, -10, job))
This code will output:
John 35 Developer
John 35Developer
John 35Developer
In conclusion, formatting rows in Python is a useful skill for any programmer. By using different techniques like the ljust()
, rjust()
, and center()
methods, the format()
method, or the %
operator, you can easily format strings and print them in a readable and organized manner.