Skip to main content

Posts

Showing posts from September, 2014

Tutorial: Using String.find() and String slicing with [n:m] notation to extract data in Python

When you need to extract data from a string in Python, you can use the built-in String.find() method in Python and the String[n:m] notation to extract the sub-string. string.find(str) will return the starting position of the first instance of str in string. For example. 'abcdecd'.find('cd') will return 2, because the first 'cd' instance starts at position 2 (not 3, since position starts with 0). If no str can be found in the string, the method will return -1. str[n:m] notation will extract the sub-string starting at position n and ending at position m-1, not including the m-th character. For example, if the content of my_str is 'I don't know', my_str[2:] will return 'don't know'. By using string.find() and [n:m] notation, we can write a script to automatically extract the data we need from a string. For example, we have a file test_score.txt that records the scores of all the students enrolled in a class. We know that each line re...