Python Friday #5: Strings

This week I was fixing a bug in a small C# method and wondered how I could do the same string manipulations in Python. Strings seem so simple, but there are many exciting details that are easy to overlook. Therefore, this post dives into strings and how we can manipulate them.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Creating Strings

Strings are immutable sequences of Unicode characters – meaning strings cannot be changed after you created them. You can create a string using '' or "", you just need to end the string in the same way as you started it:

Using "" to define the string allows you to use ' inside without the need to escape it:

(If you look closely, you notice the returned strings changed from '' to "" between the two last examples. The Python REPL translates the return values to the simplest form to represent strings).

With ''' or """ we can create a multiline string:

The \n is an escape sequence for a newline. You can find the complete list of all escape sequences in the documentation. Thanks to universal newlines in Python, we can write \n on Windows, Linux and Mac and Python will translate it to the correct form in the operating system expects (see PEP 278).

A raw string starts with an r in front and allows you to skip the escape sequences:

 

Getting help with strings

The data type of string is str. To get the extensive help and a list of all methods you can use on strings you can type this (use the letter q to quit):

 

Formatting strings

Strings are immutable, but often we need to get a string that is based on a template. The format function allows us to use these templates and replace the parts we need to customize:

With the format function you can create strings exactly as you need them. However, this flexibility comes with the price of complexity. To use it well you should check the documentation and play with the examples.

With Python 3.6 and newer you can use string interpolation. You must prefix your string with an f and then put the name of your variables between the {} (see PEP 498):

I use this style a lot in C# and I am happy that this works in Python the same way.

 

Next

With the basic data structures covered, it is time to take a closer look to control structures and the important role of whitespaces.

2 thoughts on “Python Friday #5: Strings”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.