5.7. String Check

  • str is immutable

  • str methods create a new modified str

5.7.1. Startswith, Endswith

  • str.startswith() - return True if str starts with the specified prefix, False otherwise

  • str.endswith() - return True if str ends with the specified suffix, False otherwise

  • optional start, test str beginning at that position

  • optional end, stop comparing str at that position

  • prefix/suffix can also be a tuple of strings to try

>>> email = 'alice@example.com'
>>>
>>> email.startswith('alice')
True
>>>
>>> email.startswith(('alice', 'bob'))
True
>>>
>>> email.endswith('example.com')
True
>>>
>>> email.endswith(('example.com', 'example.edu'))
True

5.7.2. Is Whitespace

  • str.isspace() - Is whitespace

  • Whitespace characters: space (`` ), newline (n``), tab (\t)

>>> data = '\t'
>>> data.isspace()
True
>>> data = '\n'
>>> data.isspace()
True
>>> data = ' '
>>> data.isspace()
True
>>> data = ''
>>> data.isspace()
False
>>> data = ' Alice '
>>> data.isspace()
False
>>> data = '\t\n '
>>> data.isspace()
True

5.7.3. Is Alphabet Characters

  • str.isalpha()

>>> text = 'hello'
>>> text.isalpha()
True
>>> text = 'hello1'
>>> text.isalpha()
False

5.7.4. Is Numeric

>>> '1'.isdecimal()
True
>>>
>>> '+1'.isdecimal()
False
>>>
>>> '-1'.isdecimal()
False
>>>
>>> '1.'.isdecimal()
False
>>>
>>> '1,'.isdecimal()
False
>>>
>>> '1.0'.isdecimal()
False
>>>
>>> '1,0'.isdecimal()
False
>>>
>>> '1_0'.isdecimal()
False
>>>
>>> '10'.isdecimal()
True
>>> '1'.isdigit()
True
>>>
>>> '+1'.isdigit()
False
>>>
>>> '-1'.isdigit()
False
>>>
>>> '1.'.isdigit()
False
>>>
>>> '1,'.isdigit()
False
>>>
>>> '1.0'.isdigit()
False
>>>
>>> '1,0'.isdigit()
False
>>>
>>> '1_0'.isdigit()
False
>>>
>>> '10'.isdigit()
True
>>> '1'.isnumeric()
True
>>>
>>> '+1'.isnumeric()
False
>>>
>>> '-1'.isnumeric()
False
>>>
>>> '1.'.isnumeric()
False
>>>
>>> '1,'.isnumeric()
False
>>>
>>> '1.0'.isnumeric()
False
>>>
>>> '1,0'.isnumeric()
False
>>>
>>> '1_0'.isnumeric()
False
>>>
>>> '10'.isnumeric()
True
>>> '1'.isalnum()
True
>>>
>>> '+1'.isalnum()
False
>>>
>>> '-1'.isalnum()
False
>>>
>>> '1.'.isalnum()
False
>>>
>>> '1,'.isalnum()
False
>>>
>>> '1.0'.isalnum()
False
>>>
>>> '1,0'.isalnum()
False
>>>
>>> '1_0'.isalnum()
False
>>>
>>> '10'.isalnum()
True

5.7.5. Find Sub-String Position

  • str.find() - Finds position of a letter in text

  • Case sensitive

  • Computers start counting from 0

  • Returns -1 if not found

>>> name = 'Alice'
>>>
>>> name.find('A')
0
>>>
>>> name.find('a')
-1
>>>
>>> name.find('ice')
2

5.7.6. Count Occurrences

  • str.count()

  • returns 0 if not found

>>> text = 'Moon'
>>>
>>>
>>> text.count('m')
0
>>>
>>> text.count('M')
1
>>>
>>> text.count('o')
2

5.7.7. References