Analysis on several Python string Methods

Source: Internet
Author: User

Analysis on several Python string Methods

Strings provide a series of methods to implement complex text processing tasks. The method is a function associated with a specific object. The method call performs two operations at the same time:

First time: attribute reading-an expression in the format of object. attribute can be understood as "reading the attribute value of an object ";

Second: The function call expression-an expression in the form of a function (parameter) means "to call the function code, pass the parameter objects separated by commas (,), and finally return the return value of the function ".

Method call expression object. The method (parameter) runs from left to right. That is to say, Python first reads the object method, calls it, and passes parameters. If a method calculates a result, it will be returned as the result of the entire method call expression.

Here, we will introduce the following methods: find, join, replace, and split.

1. find method:

Usage: S. find (sub, [, start, [, end])

NOTE: For the preceding format description, [] indicates that the parameter is optional. The parameter contained in [] is a required parameter.

The find method returns the offset at the occurrence of the substring (from the beginning to the back by default) or-1 if not found.

>>> s = 'xxxxspamxxxxspamxxxx'>>> where = s.find('spam')>>> where4

Now, if we try to implement such a replacement operation: Replace the spam string of the s string with eggs.

First, if you only Replace the first spam, you can perform the following operations:

>>> s1 = s[:where] + 'eggs' + s[(where+4):]>>> s1'xxxxeggsxxxxspamxxxx'>>>

But if we want to completely replace all spam with eggs, we have the following code changes:

>>> s = 'xxxxspamxxxxspamxxxx'>>> where = s.find('spam')>>> while where != -1 :... s = s[:where] + 'eggs' + s[(where+4):]... where = s.find('spam')... >>> s'xxxxeggsxxxxeggsxxxx'>>> 

The efficiency is very low and the amount of code is large. Therefore, we can use the replace method:

2. replace method:

Usage: S. replace (old, new, [, maxsplit])

The first parameter of this method is the original substring (any length), which replaces the string (any length) of the original substring, and then performs global search and replacement.

>>> s = 'xxxxspamxxxxspamxxxx'>>> s.replace('spam', 'eggs')'xxxxeggsxxxxeggsxxxx'>>> s'xxxxspamxxxxspamxxxx'>>> 

Here, there are several points to note:

(1) The string returned by the replace method each time is a new String object. Because the string is immutable, each method does not actually modify the string in the original place.

(2) We can control the third variable to replace it only once:

>>> s.replace('spam', 'eggs', 1)'xxxxeggsxxxxspamxxxx'>>> 

3. join method:

Usage: S. join (seq)

The join method often combines the string list into a string.

>>> s = 'spamy'>>> l = list(s)>>> l['s', 'p', 'a', 'm', 'y']>>> s'spamy'>>> 

As shown above, the list can split the string into a single character list, but the original string is not modified. Join combines the list characters into a string.

>>> l['s', 'p', 'a', 'm', 'y']>>> s'spamy'>>> ''.join(l)'spamy'>>> '+'.join(l)'s+p+a+m+y'>>> t = '***'>>> t.join(l)'s***p***a***m***y'>>> 

Here, we can draw the following conclusions:

(1) join inserts a string (called a separator) that calls this method into the merged string;

>>> '%'.join(['d','s','ld','f'])'d%s%ld%f'

(2) Through the join instance above, we can see that the number of separators is always equal to the number of list elements-1.

(3) The merged string will be stored in the memory without modifying the list object.

4. split method:

Usage: S. split ([seq, [, maxsplit])

The split method splits the string and stores the substring in the list object.

>>> x = 'iperf -u -c 192.168.1.1'>>> x.split()['iperf', '-u', '-c', '192.168.1.1']>>> x = 'iperf -u -c 192.168.1.1'>>> x.split()['iperf', '-u', '-c', '192.168.1.1']>>> 

The above is the default Use Case of the split function. Through these instances, we can see that the default split method is used to separate strings by spaces, regardless of the number of spaces (greater than or equal to 1 ). Of course, from the above example, we can see that the default split method is often used as a command line analysis tool.

Now, we analyze the optional parameters:

>>> s = 'www.baidu.com'>>> s.split()['www.baidu.com']>>> s.split(',')['www.baidu.com']>>> s.split('.')['www', 'baidu', 'com']

With the code above, the optional parameter is the delimiter used to separate strings. In addition, the default split method cannot separate strings without spaces.

Now, let's try another way:

>>> s = r'www.baidu.com/zhidao/cpp/format/2015-1-5-22-10'>>> s'www.baidu.com/zhidao/cpp/format/2015-1-5-22-10'>>> s.split()['www.baidu.com/zhidao/cpp/format/2015-1-5-22-10']>>> s.split('.')['www', 'baidu', 'com/zhidao/cpp/format/2015-1-5-22-10']>>> s.split(r'/')['www.baidu.com', 'zhidao', 'cpp', 'format', '2015-1-5-22-10']>>> s.split('-')['www.baidu.com/zhidao/cpp/format/2015', '1', '5', '22', '10']>>> s.split(['.','//','-'])Traceback (most recent call last):File "
 
  ", line 1, in 
  
   TypeError: expected a character buffer object
  
 

If we try to get the expected data at the same time for the above string with multiple meaningful delimiters, it is not feasible to set the list object in the optional parameter.

In many cases, it is better to use regular expressions to obtain results separated by multiple delimiters.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.