DEV Community

Cover image for The Top 5 String Manipulation Functions You Forgot To Pack

The Top 5 String Manipulation Functions You Forgot To Pack

Abdur-Rahmaan Janhangeer
Cruising python seas. Independent Py Dev
Originally published at ・2 min read

Python provides a lot of cool and convenient string manipulation functions that people always re-invent. Python is powerful and ... thoughtful. We were strict and choose only 5, the five best. Hope you enjoy it!

What are string manipulation functions?

String manipulation functions are helper functions used to manipulate strings. If you have let us say 'ABC', a nice lowercase function would transform it to 'abc'. Let us begin our count.

1. str.swapcase()

Programmers are familiar with .upper() and .lower() and try to implement case swapping using those two. .swapcase() you've guessed it automatically converts the case.

>>> x = 'aaaBBB'
>>> x.swapcase()


Use of swapcase

2. str.zfill()

Let's say you want to build a nice table to display numbers as


If you don't want to worry about indexes etc, zfill is your buddy.

>>> '1234'.zfill(7)


zfill() fills in the missing zeros for the given width.

Use of zfill

3. str.casefold()

Casefold is used to compare strings. It attempts to do so following unicode.

if 'ABC'.casefold() == 'aBc'.casefold():

Question: Is that not the same as str.lower()?

Answer: casefold() is a unicode compliant version, which is not the case for str.lower()

Use of casefold

4. center()

center() is used to center texts. A cool neatify tool out of the box.

>>> 'abcd'.center(10)

'   abcd   '

It also supports a fillchar parameter

>>> 'abcd'.center(10, '?')


Use of center

5. expandtabs()

That one makes real sense in Python. Let's say you are replacing tabs while reading a python source file or just converting tabs to spaces while building an editor. just do ''.expandtabs() and it will be converted!

>>> print('''   abcd


Use of expandtabs

Python has coool string manipulation functions. We promised 5 and here they are.

Discussion (0)