How to Format String using center() Method

The center() method is a built-in method in Python’s str class that returns a new string that is centered within a string of a specified width. 

Formatting string using center() method

This code returns a new string padded with spaces on the left and right sides.

Python3




string = "w3wiki!"
width = 30
 
centered_string = string.center(width)
 
print(centered_string)


Output

        w3wiki!        

Python String Formatting – How to format String?

String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string.

You will learn different methods of string formatting with examples for better understanding. Let’s look at them now!

Similar Reads

How to Format Strings in Python

There are five different ways to perform string formatting in Python...

1. How to Format String using % Operator

It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known as the “string-formatting operator”....

2. How to Format String using format() Method

...

3. Understanding Python f-string

...

4. Python String Template Class

...

5. How to Format String using center() Method

...

Python Format String: % vs. .format vs. f-string literal

Format() method was introduced with Python3 for handling complex string formatting more efficiently....