Differences
This shows you the differences between two versions of the page.
python_wiki:string_matching [2019/05/25 23:50] |
python_wiki:string_matching [2019/05/25 23:50] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== String Matching ====== | ||
+ | |||
+ | **General Information** | ||
+ | |||
+ | Different string functions for matching. | ||
+ | |||
+ | **Checklist** | ||
+ | * Python 2 or 3 | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ====== Usage ====== | ||
+ | |||
+ | Using the code snippet. | ||
+ | <code bash> | ||
+ | chmod +x string-matching.py | ||
+ | ./ | ||
+ | </ | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ====== The Code ====== | ||
+ | |||
+ | <code python string-matching.py> | ||
+ | # | ||
+ | |||
+ | # strings for testing | ||
+ | my_string1=" | ||
+ | my_string2=" | ||
+ | my_string3=" | ||
+ | my_string4=" | ||
+ | |||
+ | my_string_list = [my_string1, | ||
+ | |||
+ | for string in my_string_list: | ||
+ | |||
+ | # Starts with matching | ||
+ | if string.startswith(" | ||
+ | print(string + " matched a ' | ||
+ | |||
+ | # Matching slice: character at index 1 up to, but not including index 2 | ||
+ | # string indexes start at 0 = the 2nd character in the string. | ||
+ | if string.startswith(" | ||
+ | print(string + " matched a ' | ||
+ | |||
+ | # Ends with matching | ||
+ | if string.endswith(" | ||
+ | print(string + " matched a ' | ||
+ | |||
+ | # Find a string within a string (returns -1 if not found) | ||
+ | if string.find(" | ||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | ---- | ||