String Manipulation Functions: The Top 5 You Forgot To Pack

String Manipulation Functions: The Top 5 You Forgot To Pack

String manipulation functions, good ones are available by default in Python. Ignorance make 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.

book case string

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()

'AAAbbb'

Use of swapcase

2. str.zfill()

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

3. str.casefold()

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

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, '?')


'???abcd???'

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
        abcd
    abcd'''.expandtabs(4))

    abcd
        abcd
    abcd

Use of expandtabs

Python has coool string manipulation functions. We promised 5 and here they are. In the days of viral 10x engineer contents, the casual programmer got high standards to conform to. One of them is knowing the docs thoroughly. But, string functions are a higher priority!

Talking of strings, you might want to know how to handle curly braces in string formatting.

  •  
  •  
  •  
  •  

Lives in Mauritius, cruising python waters for now.