Python字符串替换如何才能进行字符的拆分


Python字符串替换需要我们不断的进行学习,只有不断的学习才能更好的进行使用。下面我们就来看看如何在实际使用中进行相关Python字符串替换。这回在以后的使用中对你有所帮助。

Python字符串替换

替换所有匹配的子串。用newstring替换subject中所有与正则表达式regex匹配的子串

  1. result, number = re.subn(regex, newstring, subject)  
  2. 替换所有匹配的子串使 用正则表达式对象)  
  3. rereobj = re.compile(regex)  
  4. result, number = reobj.subn(newstring, subject)字符串拆分 

字符串拆分

  1. reresult = re.split(regex, subject)  
  2. 字符串拆分使用正则表示式对象)  
  3. rereobj = re.compile(regex)  
  4. result = reobj.split(subject)匹配 

下面列出Python正则表达式的几种匹配用法:

测试正则表达式是否 匹配字符串的全部或部分
 

  1. regex=ur"..." #正则表达式  
  2. if re.search(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing()  

测试正则表达式是否匹配整个字符串

  1. regex=ur"...\Z" #正则表达式末尾以\Z结束  
  2. if re.match(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

创建一个匹配对象,然后通过该对象获得匹配细节

  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. # match start: match.start()  
  5. # match end (exclusive): match.end()  
  6. # matched text: match.group()  
  7. do_something()  
  8. else:  
  9. do_anotherthing() 

以上就是对Python字符串替换的相关介绍。

相关内容

    暂无相关文章

评论关闭