pu71n@pu71n.github.io:/$ cat Python - Manipulating Strings

Typing string values in Python code is fairly straightforward: They begin and end with a single quote or double quotes. The benifit of using the double quotes is that string can have a single quote character in it.

Escape Characters

An escape character lets you use characters that are otherwise impossible to put into a string. An escape character consists of a backslash () foloowed by the character you want to add to the string.

| Escape character    | Prints as    |
|---------------------|--------------|
| \'                  | Single quote |
| \"                  | Double Quote |
| \t                  | tab          |
| \n                  | Newline      |
| \\                  | Backslash    |

Raw Strings

You can place an r before the beginning quotation mark of a string to make it a raw string : a raw string completely ignores all escape characters and prints any backslash that appears in the string.

Multiline Strings with Triple quotes

While you can use the \n escape character to put a newline into a tring, it is often easier to use multiline strings. A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the triple quotes are considered part of the string. Python’s indentation rules for blocks do not apply to lines inside a multiline string.

Multiline Comments

While the hash character (#) marks the beginning of a comment for the rest of the line, a multiline string is often used for comments that span multiple lines.

Indexing and Slicing String

Strings use indexes and slices the same way lists do. You can think of the string “I’m putin” as a list and each character in the string as an item with a corresponding index. If you specify an index, you’ll get the character at that position in the string. If you specify a range from one index to another, the starting index id included and the ending index is not.

The in and not in Operators with Strings

The in and not in operators can be used with strings just like with list values. An expression with two strngs joined using in or not in will evaluate to boolean True or False.

Useful String Methods