Creating parts of strings

As we have seen before the find(string) function takes a target string as input and returns the index where that target string is found in the current string. If the string isn’t found it returns -1.

Note

The find function will return the first position it finds the given string in. Notice that above it printed 2 which means it found the “is” in “This” first.

Check your understanding

    csp-17-6-1: What will be printed when the following executes?

    a_str = "His shirt is red"
    pos = a_str.find("is")
    print(pos)
    
  • 1
  • The find function returns the index of the first position that contains the given string.
  • 9
  • This would be true if it was pos = str.find(" is").
  • 10
  • This would be true if it was pos = str.find(" is") and the first position was 1, but it is 0.
  • -1
  • A -1 is returned if the string you are looking for isn't found.

    csp-17-6-2: What will be printed when the following executes?

    a_str = "His shirt is red"
    pos = a_str.find("Red")
    print(pos)
    
  • 1
  • Why would this return 1? What string was it looking for and where is that string in a_str
  • 13
  • This would be true if it was a_str.find("red").
  • 14
  • This would be true if it was a_str.find("red") and the first position was 1, but it is 0.
  • -1
  • A -1 is returned when the string you are looking for isn't found. Remember that case matters in Python!

You can use the find function along with the slice feature to get part of a string. To get a slice (part) of a string use string_name[start:end], which returns a new string with all the characters from the start position to one before the end position.

Say that you are looking for a name in a string but don’t know the exact position of the name in the string. However you do know that it will be after name:.

Next Section - Chapter 17 - Concept Summary