Salvatore Lopiparo

Software Engineer

Super Simple Python #14 – Advanced Strings and Formatting

We dealt with some simple string stuff early on, but it was fairly limited in what you can do. In this lesson, I’ll teach you all the fancy stuff they don’t teach you in grade school! (Actually, I’m not sure they teach any of this stuff in grade school.)

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Special Characters

There are two special white-space characters that are useful to know and are used commonly: newline, \n, and tab, \t. They are known as white-space characters because they don’t actually draw a character. They are invisible characters, similar to a space from the space bar (as opposed to a space martini from the Space Bar).

The tab character \t adds a large space as if you hit the “Tab” key on the keyboard. It can be useful when you want to do some simple formatting.

>>> balloons = {'red': 12, 'blue': 8, 'green': 14}
>>> for color in balloons:
...     print(color + '\t\t' + str(balloons[color]))
red     12
blue        8
green       14

The newline character \n is an invisible character that means “start writing on the next line”. It is used when you have a long string that would look nicer on two lines.

>>> for color in balloons:
...     print("The number of " + color + ' balloons is on the next line!\n\t' + str(balloons[color]))
The number of red balloons is on the next line!
The number of blue balloons is on the next line!
The number of green balloons is on the next line!

Sometimes you may want to have an actual backslash before the letter ‘n’. In this case, you must escape the backslash: \\n. A single backslash says “THE NEXT CHARACTER IS SPECIAL!” A double backslash says “THE NEXT CHARACTER IS NOT SPECIAL, I AM!”

>>> print('before\nafter')
>>> print('before\\nafter')

Raw Strings

There are a couple special string types that are not commonly used, but one is worth mentioning. The raw string type takes any special characters and escapes them automatically. You can write a raw string by putting an r directly in front of the string: r'my string'. Note in the following example that we use \n for \name.txt, but because we’re using raw it escapes the character for us.

>>> # This will auto-escape! The path will be complete!
>>> raw_file_path = r"C:\some\path\name.txt"
>>> raw_file_path
>>> print(raw_file_path)
>>> # This will NOT escape! The path will be broken!
>>> non_raw_path = "C:\some\path\name.txt"
>>> non_raw_path
>>> print(non_raw_path)


Your email address will not be published. Required fields are marked *