Home > Article > Backend Development > Example tutorial of partition string function in Python
In version 2.5Newadded a function called partition. What can it do? Give a small example:
>>> 'http://www.donews.net/limodou'.partition('://')
('http', '://', 'www.donews.net/limodou')
>>> 'file:/a.html'.partition('://')
('file:/ a.html', ”, ”)
list. If it is found, it returns a 2-yuan list. If it is not found, it returns a 1-yuan list, such as:
>>> ‘a.b.c’.split(‘,’, 1) ['a.b.c'] >>> ‘a.b.c’.split(‘.’, 1) ['a', 'b.c']At the same time, it does not return the delimiter if found. In some cases partition(sep) and rpartition(sep) (matching from right to left) have similar functions to split(sep, 1) and rsplit(sep, 1). However, partition is actually created to replace find and index, not split. In many cases, we need to find a location first and then split it. It is much more convenient to use partition. For example:
>>> a = ‘http://www.donews.net’ >>> pos = a.find(‘://’) >>> if pos > -1: … print a[:pos], a[pos+1:] http www.donews.netIs it simpler to use partition:
>>> a = ‘http://www.donews.net’ >>> left, sep, right = a.partition(‘://’) >>> print left, right http www.donews.net? At the same time, in version 2.5, startswith and endswith have changed, and their first parameter can be a tuple. This is very convenient when judging several situations. For example, if you want to determine the file name suffix, when it originally only supported one value, you may have to split it first and then determine it. Endswith is not needed, such as:
>>> a = ‘a.gif’ >>> import os.path >>> ext = os.path.splitext(a)[1] >>> if ext in ['.gif', '.png', '.bmp']: … print ‘found’ … foundBut now you can:
>>> a = ‘a.gif’ >>> if a.endswith((‘.gif’, ‘png’, ‘.bmp’)): … print ‘found’ … foundIs that right? Much simpler. Note that the above tuple does not work if I replace it with a list. It seems to be mandatory. Many interesting things are waiting for you and me to discover. 【Related recommendations】
Share a detailed explanation of the string function (partition) in Python
2.Share an example code of a string function (partition)
3.MySQL-A brief analysis of code examples of data table partitioning technology PARTITION
The above is the detailed content of Example tutorial of partition string function in Python. For more information, please follow other related articles on the PHP Chinese website!