6.7. String Check — Python
stris immutablestrmethods create a new modifiedstr
6.7.1. Startswith, Endswith
str.startswith()- returnTrueifstrstarts with the specified prefix,Falseotherwisestr.endswith()- returnTrueifstrends with the specified suffix,Falseotherwiseoptional
start, teststrbeginning at that positionoptional
end, stop comparingstrat 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
6.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
6.7.3. Is Alphabet Characters
str.isalpha()
>>> text = 'hello' >>> text.isalpha() True
>>> text = 'hello1' >>> text.isalpha() False
6.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
6.7.5. Find Sub-String Position
str.find()- Finds position of a letter in textCase sensitive
Computers start counting from 0
Returns
-1if not found
>>> name = 'Alice' >>> >>> name.find('A') 0 >>> >>> name.find('a') -1 >>> >>> name.find('ice') 2
6.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