Python 字符串的删除和替换

来源:互联网 发布:linux tomcat部署 编辑:程序博客网 时间:2024/05/22 08:21

Python 字符串的删除和替换 

一、删除   1.str.strip()去掉字符串两边的空格,\n。   2.lstrip()去掉字符串左侧。   3.rstrip()去掉字符串右侧。

str_01 = ' xiong   da\n'print str_01.strip()        # ---> xiong   dastr_02 = '-----xiong da-------'print str_02.lstrip('-')    # ---> xiong da-------
二、替换
# 01:去掉(\t\n\a)str_01 = '\twww.\abaidu.   com\n'# 修改字符串def modifyStr(s):    s = s.replace('\n','')    s = s.replace('\t','')    s = s.replace('\a','')    s = s.replace(' ','')    return sprint modifyStr(str_01)     # ---> www.baidu.com# 02:re模块中的sub.字符串替换import restr_02 = 'hello    world   'str_02 = str_02.strip()# 将hello   world中间所有的空格替换为一个空格print re.sub(r'\s+', ' ', str_02) # ---> hello worldprint re.sub('[abc]', 'o', 'Mark') # ---> Mork




0 0
原创粉丝点击