In Python-lingo, strings are an "immutable" object type, which means that they cannot be changed in place; the only way to alter a string is to create a new string with the changes. Python comes with powerful built-in operators designed to make it easier to extract subsections of a string, and thereby create new strings. For example, to extract the letter "b" from the string "hobgoblin", I could use This is referred to as "slicing"; the square braces [ and ] specify the starting and ending location (or "index") for the slice. Note that the first character is referred to by index 0. You can extract a substring by specifying two indices within the square braces... ...and watch what happens when I omit either one of the two indices. You can also use negative indices, to force Python to begin counting from the right instead of the left. The built-in len() function can be used to calculate the number of characters in a string, while the "in" and "not in" operators can be used to test for the presence of a particular character in a string. A match returns 1 (true), while a failure returns 0 (false).
blog comments powered by Disqus |