示例:
替换字符串开头和结尾处的空格
1. [代码][Python]代码 跳至 [1] [全屏预览]
01 | # -*- coding: utf-8 -*- |
02 |
03 | #替换字符串开头的空格 |
04 | i=0 |
05 | while s[i].isspace(): |
06 | i=i+1 |
07 | else: |
08 | ss=s[0:i].replace(' ','*') |
09 | s=ss+s[i:] |
10 | print s |
11 |
12 | #替换字符串结尾的空格 |
13 | i=-1 |
14 | while s[i].isspace(): |
15 | i=i-1 |
16 | else: |
17 | ss=s[i+1:].replace(' ','*')#list 用负数进行索引时,[a:-1],-1仍然是取不到的 |
18 | s=s[:i+1]+ss |
19 | print s |
转自:http://www.oschina.net/code/snippet_121336_3349
strip
函数原型
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
1. 当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
例如:
>>> a = ' 123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'
2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
例如 :
>>> a = '123abc'
>>> a.strip('21')
'3abc' 结果是一样的
>>> a.strip('12')
'3abc'
Python中的strip用于去除字符串的首尾字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。
这三个函数都可传入一个参数,指定要去除的首尾字符。
需要注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如:
theString
=
'saaaay yes no yaaaass'
print
theString.strip(
'say'
)
|
theString依次被去除首尾在['s','a','y']数组内的字符,直到字符在不数组内。所以,输出的结果为:
yes no
比较简单吧,lstrip和rstrip原理是一样的。
注意:当没有传入参数时,是默认去除首尾空格的。
theString
=
'saaaay yes no yaaaass'
print
theString.strip(
'say'
)
print
theString.strip(
'say '
)
#say后面有空格
print
theString.lstrip(
'say'
)
print
theString.rstrip(
'say'
)
|
运行结果:
yes no
es no
yes no yaaaass
saaaay yes no
本文详细介绍了Python中字符串的strip、lstrip和rstrip方法的使用技巧。这些方法用于去除字符串首尾的特定字符,尤其在处理带有空白字符的数据时非常有用。文章通过实例展示了不同情况下如何灵活运用这些方法。
1316







1# -* -coding:UTF-8 -*-2s=' test string '3print(len(s)-len(s.lstrip()))*'*'+s.strip()+(len(s)-len(s.rstrip()))*'*'45***test string***