How to Create Strings with Special Characters in Python - dummies

How to Create Strings with Special Characters in Python

By John Paul Mueller

Some strings in Python programming include special characters. These characters are different from the alphanumeric and punctuation characters that you’re used to using. In fact, they fall into these categories:

  • Control: An application requires some means of determining that a particular character isn’t meant to be displayed but rather to control the display. All the control movements are based on the insertion pointer, the line you see when you type text on the screen.

    For example, you don’t see a tab character. The tab character provides a space between two elements, and the size of that space is controlled by a tab stop. Likewise, when you want to go to the next line, you use a carriage return (which returns the insertion pointer to the beginning of the line) and linefeed (which places the insertion pointer on the next line) combination.

  • Accented: Characters that have accents, such as the acute (‘), grave (`), circumflex (^), umlaut or diaeresis (¨), tilde (~), or ring (̊), represent special spoken sounds, in most cases. You must use special characters to create alphabetical characters with these accents included.

  • Drawing: It’s possible to create rudimentary art with some characters. Check out examples of the box-drawing characters. Some people actually create art using ASCII characters as well.

  • Typographical: A number of typographical characters, such as the pilcrow (¶),are used when displaying certain kinds of text onscreen, especially when the application acts as an editor.

  • Other: Depending on the character set you use, the selection of characters is nearly endless. You can find a character for just about any need. The point is that you need some means of telling Python how to present these special characters.

A common need when working with strings, even strings from simple console applications, is control characters. With this in mind, Python provides escape sequences that you use to define control characters directly (and a special escape sequence for other characters).

An escape sequence literally escapes the common meaning of a letter, such as a, and gives it a new meaning (such as the ASCII bell or beep). The combination of the backslash () and a letter (such as a) is commonly viewed as a single letter by developers — an escape character or escape code. Here’s an overview.

Escape Sequence Meaning
newline Ignored
\ Backslash ()
Single quote (‘)