text string matching

libertycodervice

libertycodervice

Posted on March 4, 2020

text string matching

In Python programming, if you have a string you can do comparison or so called string matching.

Matches the beginning or end of the string is generally used in the matching file type or url

Simple text matching

A simple matching function is the general startwith() function.

>>> a = 'http://www.python.org'
>>> a.startswith ( 'http')
True

Note: This parameters which can be string, can also be a tuple. The example below passes a tuple as argument with two values.

>>> a = 'http://www.python.org'
>>> a.startswith (( 'http', 'ftp'))
True

As you may have guessed, you can also use the method endswith(), with a string or tuple.

>>> a = 'https://python.org'
>>> a.endswith(( '.org','.com' ))
True
>>> 

While tuples are similar to lists, lists are not allowed as parameter.

The parameter can not be lists or dictionary. If you try a list or dictionary, then you get an error

>>> a = 'http://www.python.org'
>>> a.startswith ([ 'http', 'ftp'])
Traceback (most recent call last):
File "", line 1, in
a.startswith ([ 'http', 'ftp'])
TypeError: startswith first arg must be str or a tuple of str, not list
>>>

In fact, in addition to the above method, you can also use slices to achieve matching, but the code looks not so good:

>>> a = 'https://www.python.org'
>>> a[0:4] == 'https'
True
>>>

Regular expressions

Of course, we can also use regular expressions to do this, but on top of it a little difficult to understand a little.

>>> import re
>>> url = 'http://www.python.org'
>>> re.match ( 'http: | https: | ftp:', url)
0, 5), match = 'http:'>
>>> help (re.match)
Help on function match in module re:
      
match (pattern, string, flags = 0)
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.
 
>>>
💖 💪 🙅 🚩
libertycodervice
libertycodervice

Posted on March 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024