Python字符串处理与正则表达式实战指南

Elena
Elena
发布时间:2026-10-14 | 4人浏览过
原创

本文深入解析Python中字符串搜索、替换及格式化的常用方法。重点介绍如何使用str.replace()处理简单模式,利用re.sub()结合正则表达式处理复杂文本替换,并通过re.IGNORECASE标志实现忽略大小写的匹配。此外,还涵盖了利用ljust/rjust/center及format()函数进行字符串对齐格式化的具体技巧,帮助开发者高效处理文本数据。

字符串搜索与文本模式匹配

一、在字符串中搜索和匹配指定文本模式

需要补充的是,re模块同样是处理字符串的强大工具。以往我们可能倾向于使用内置函数,但对于复杂的文本结构和数据模式,re模块能提供更高效的解决方案。

针对简单的字面量模式,直接使用str.replace()方法即可满足需求。例如:

>>> text = 'yeah, but no, but yeah, but no, but yeah' >>> text.replace('yeah', 'yep') 'yep, but no, but yep, but no, but yep' >>>

对于更复杂的模式匹配,应使用re模块中的sub()函数。假设需要将日期格式从11/27/2012转换为2012-11-27,示例如下:

>>> text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' >>> import re >>> re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) 'Today is 2012-11-27. PyCon starts 2013-3-13.'

忽略大小写的文本搜索与替换

二、忽略大小写搜索与替换文本字符串

若要在文本操作中忽略大小写,需在调用re模块相关操作时传入re.IGNORECASE标志参数。例如:

>>> text = 'UPPER PYTHON, lower python, Mixed Python' >>> re.findall('python', text, flags=re.IGNORECASE) ['PYTHON', 'python', 'Python'] >>> re.sub('python', 'snake', text, flags=re.IGNORECASE) 'UPPER snake, lower snake, Mixed snake'

上述示例揭示了一个小问题:替换字符串不会自动保持与被匹配字符串相同的大小写风格。为解决此问题,可以定义一个辅助函数,如下所示:


def matchcase(word):
  def replace(m):
    text = m.group()
    if text.isupper():
      return word.upper()
    elif text.islower():
      return word.lower()
    elif text[0].isupper():
      return word.capitalize()
    else:
      return word
  return replace

>>> re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) 'UPPER SNAKE, lower snake, Mixed Snake'

matchcase('snake')返回一个回调函数,该函数接收match对象作为参数。sub()函数除了接受替换字符串外,还支持接收此类回调函数以动态生成替换结果。

跨行文本的正则表达式匹配

三、跨越多行匹配大块文本的正则表达式应用

>>> comment = re.compile(r'/\*(.*?)\*/') >>> text1 = '/* this is a comment */' >>> text2 = '''/* this is a ... multiline comment */ ... ''' >>> >>> comment.findall(text1) [' this is a comment '] >>> comment.findall(text2)

此时,re.compile()函数中的re.DOTALL标志显得尤为重要。该标志允许正则表达式中的点号(.)匹配包括换行符在内的任意字符。例如:

>>> comment = re.compile(r'/\*(.*?)\*/', re.DOTALL) >>> comment.findall(text2) [' this is a\n multiline comment ']

字符串对齐与格式化技巧

四、通过特定对齐方式格式化字符串

对于基本的字符串对齐操作,可以使用字符串的ljust()、rjust()和center()方法。例如:

>>> text = 'Hello World' >>> text.ljust(20) 'Hello World ' >>> text.rjust(20) ' Hello World' >>> text.center(20) ' Hello World ' >>> text.rjust(20,'=') '=========Hello World' >>> text.center(20,'*') '****Hello World*****' >>>

format()函数同样可以轻松实现字符串对齐。只需在<、>或^字符后指定宽度即可。例如:

>>> format(text, '>20') ' Hello World' >>> format(text, '<20') 'Hello World ' >>> format(text, '^20') ' Hello World ' >>>

若需指定非空格填充字符,只需将其置于对齐字符之前。例如:

>>> format(text, '=>20s') '=========Hello World' >>> format(text, '*^20s') '****Hello World*****' >>>

当格式化多个值时,这些格式代码也可应用于format()方法中。例如:

>>> x = 1.2345 >>> format(x, '>10') ' 1.2345' >>> format(x, '^10.2f') ' 1.23 ' >>>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表