str
=
"0000000this is string example....wow!!!0000000"
;
print
str
.
strip
(
'0'
);
以上实例输出结果如下:
this is string example....wow!!!
函数原型
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
(1)当rm为空时,默认删除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ‘)
(2)这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
>>> a = ' 123'
' 123'
>>> a.strip()
'123'
(2)这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
>>> a = '123abc'
>>> a.strip('21')
'3abc'
>>> a.strip('12')
'3abc'
结果是一样的。
python strip() 函数和 split() 函数的详解及实例
一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意思。因此也表示了这两个功能是完全不一样的,strip可以删除字符串的某些字符,而split则是根据规定的字符将字符串进行分割。下面就详细说一下这两个功能,
1 Python strip()函数 介绍
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
(1)当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
(2)这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
>>> str_split
=
str
.split(
'.'
)[::
-
1
]
>>>
print
str_split
[
'cn'
,
'com'
,
'com'
,
'google'
,
'www'
]
>>> str_split
=
str
.split(
'.'
)[:
-
1
]
>>>
print
str_split
[
'www'
,
'google'
,
'com'
,
'com'
]
>>> ip2num
=
lambda
x:
sum
([
256
*
*
j
*
int
(i)
for
j,i
in
enumerate
(x.split(
'.'
)[::
-
1
])])
>>> ip2num(
'192.168.0.1'
)
3232235521
>>> num2ip
=
lambda
x:
'.'
.join([
str
(x
/
(
256
*
*
i)
%
256
)
for
i
in
range
(
3
,
-
1
,
-
1
)])
>>> num2ip(
3232235521
)
'192.168.0.1'
>>>
import
struct
>>> int_ip
=
123456789
>>> socket.inet_ntoa(struct.pack(‘I',socket.htonl(int_ip)))
‘
7.91
.
205.21
'
>>>
str
(socket.ntohl(struct.unpack(“I”,socket.inet_aton(“
255.255
.
255.255
″))[
0
]))
‘
4294967295
'