5.7. String Check
str
is immutablestr
methods create a new modifiedstr
5.7.1. Startswith, Endswith
str.startswith()
- returnTrue
ifstr
starts with the specified prefix,False
otherwisestr.endswith()
- returnTrue
ifstr
ends with the specified suffix,False
otherwiseoptional
start
, teststr
beginning at that positionoptional
end
, stop comparingstr
at that positionprefix/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 whitespaceWhitespace 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
str.isdecimal()
str.isdigit()
str.isnumeric()
str.isalnum()
>>> '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 textCase 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