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!
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.
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() 'AAAbbb'
Use of swapcase
Let's say you want to build a nice table to display numbers as
0000123 0025378 0005234 0012374
If you don't want to worry about indexes etc, zfill is your buddy.
>>> '1234'.zfill(7) '0001234'
zfill() fills in the missing zeros for the given width.
Use of zfill
Casefold is used to compare strings. It attempts to do so following unicode.
if 'ABC'.casefold() == 'aBc'.casefold(): pass
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
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, '?') '???abcd???'
Use of center
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 abcd abcd'''.expandtabs(4)) abcd abcd abcd
Use of expandtabs
Python has coool string manipulation functions. We promised 5 and here they are.