Skip to content
Home » String Formatting Methods in Python

String Formatting Methods in Python

Spread the love

Today we’ll be talking about string formatting methods.

Here’s the video version of the article:

If you haven’t read my previous articles on formatting strings, feel free to read them. Here they are:

1) the basics of formatting with the format method and f-strings,

2) advanced string formatting with the format method

3) using dictionaries to format strings

4) the string format operator

There are plenty of built-in string methods to make our life easier. Many methods can work not only on whole strings, but also on substrings enclosed between a start index and an end index. These two parameters are optional, but if they are passed to the method, they work just like in slicing, so the end index is exclusive.

Here are the most important formatting methods:

string formatting methods

And now let’s have a look at them in more detail.

Capitalization

We have a couple of methods to handle capitalization. One of them is capitalize, which returns a copy of the string with the first character capitalized and the other characters in lowercase:

>>> sentence = "this is a sentence."
>>> sentence.capitalize()
'This is a sentence.'

And here’s how it works with an all-uppercase string:

>>> text = "NO ENTRY"
>>> text.capitalize()
'No entry'

Methods may also work on literals:

>>> "this is a sentence.".capitalize()
'This is a sentence.'

If we want to turn all letters to uppercase, we should use the upper method:

>>> "Don't touch it!".upper()
"DON'T TOUCH IT!"

If we want to turn all letters to lowercase, we should use the lower method:

>>> "Just the 24 years in PRISON!".lower()
'just the 24 years in prison!'

We can also swap case: turn all lowercase characters to uppercase and vice-versa. We can do it by using the method swapcase:

>>> text = '"DON\'T DO IT!", she demanded.'
>>> text.swapcase()
'"don\'t do it!", SHE DEMANDED.'

The method title returns a copy of the string in titlecase, so with each word beginning with a capital letter:

>>> book_title = "A short history of what never happened"
>>> print(book_title.title())
A Short History Of What Never Happened

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Alignment, Tabbing, Padding

There are a few methods to help us align text. One of them is center(width[, fillchar]). This method returns a string which is at least width characters wide and aligned centrally. If the string is wider than the original, the remaining space is padded with the optional fillchar character. The default fillchar character is space:

>>> text = 'example'
>>> text.center(20)
'      example       '
>>> text.center(20, "*")
'******example*******'

A similar method is ljust(width[, fillchar]). This method returns a string which is left-justified and width characters wide. If width is less than the length of the string, the original string is returned. If the string is wider than the original, the remaining space is padded with the optional fillchar character. The default fillchar character is space:

>>> text = "wow!!!"
>>> text.ljust(50)
'wow!!!                                            '
>>> text.ljust(50, "!")
'wow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'

The method rjust(width[, fillchar]) returns a string which is right-justified. If width is less than the length of the string, the original string is returned. If the string is wider than the original, the remaining space is padded with the optional fillchar character. The default fillchar character is space:

>>> text = "...and so she did."
>>> text.rjust(50)
'                                ...and so she did.'
>>> text.rjust(50, ".")
'...................................and so she did.'
>>>

We can pad our string on the left with zeros using the zfill(width) method. The width parameter is for the width of the padded string including both the original string and the padding:

>>> text = "abcdef"
>>> text.zfill(20)
'00000000000000abcdef'

If width is smaller than the width of the string, there is no padding:

>>> text.zfill(3)
'abcdef'

If the string begins with a leading sign (+ or -), the zeros are added after the sign:

>>> "-45".zfill(5)
'-0045'
>>> "+38".zfill(10)
'+000000038'

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

The expandtabs([tabsize]) returns a string with the tab character (\t) expanded to the size of tabsize. If no parameter is passed, the default tabsize is 8. Here’s a text with a tab:

>>> text = "Hey, \twait!"
>>> print(text)
Hey, 	wait!

expandtabs has no effect if tabsize equals 8 or is omitted:

>>> print(text.expandtabs())
Hey,    wait!

>>> print(text.expandtabs(8))
Hey,    wait!

We can see the effect with other values of tabsize:

>>> print(text.expandtabs(16))
Hey,            wait!

>>> print(text.expandtabs(32))
Hey,                            wait!

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply