Introduction to python strip of function

  • 2020-04-02 13:10:37
  • OfStack

describe
The Python strip() method is used to remove the characters specified at the beginning and end of a string (space by default).

grammar
Strip () method syntax:
STR. Strip ([chars]);

parameter
Chars - removes the character specified at the beginning and end of the string.
The return value
Returns a new string generated by removing the character specified at the beginning and end of the string.

The instance
The following example shows how to use the strip() function:


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "0000000   jb51.net 0000000"
print(str.strip( '0' )) #  Remove prefix and trailing characters  0 
 
str2 = "  jb51.net   "  #  Remove headspace 
print(str2.strip())

The output results of the above examples are as follows:

        jb51.net  
jb51.net

Python3 the replace () method

describe
The replace() method replaces the old (old string) in the string with new(new string) no more than Max times if the third parameter Max is specified.

grammar
Replace () method syntax:

STR. Replace (old and new [, Max])
parameter
Old -- the substring to be replaced.
New -- new string to replace the old substring.
Max -- optional string with no more than Max substitutions
The return value
Returns the new string generated after the old (old string) in the string is replaced with new(new string), and is replaced no more than Max times if the third parameter Max is specified.

The instance
The following example shows how to use the replace() function:


#!/usr/bin/python3
 
str = " Welcome to script house www.jb51.net"
print (" Old address of script house: ", str)
print (" Script house new address: ", str.replace("jb51.net", "jbzj.com"))
 
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))

The output results of the above examples are as follows:

Old address of this site: www.jbzj.com
New address for this site: www.jb51.net
Thwas the was string example... Wow!!!!!!

The function prototype

Declaration: s is a string and rm is a sequence of characters to be deleted

S.trip (rm) deletes the character at the beginning and end of the s string in the rm deletes sequence
S.strip (rm) deletes the character at the beginning of the s string in the rm deletes sequence
S.strip (rm) deletes the character at the end of the s string, located in the rm deletes sequence

Note:

1. When rm is empty, empty characters (including '\n', '\r', '\t', ' ') are deleted by default.

Such as:


>>> a = '   123'
>>> a.strip()
'123'
>>> a='ttabc'
'abc'
>>> a = 'sdffrn'
>>> a.strip()
'sdff'

2. The rm delete sequence here is deleted as long as the character on the edge (beginning or end) is in the delete sequence.

Such as:


>>> a = '123abc'
>>> a.strip('21')
'3abc'   The result is the same 
>>> a.strip('12')
'3abc'

The article is here, the need for a friend can refer to


Related articles: