当前位置: 移动技术网 > IT编程>脚本编程>Python > Python字符串及文本模式方法详解

Python字符串及文本模式方法详解

2020年09月11日  | 移动技术网IT编程  | 我要评论
一、你想在字符串中搜索和匹配指定的文本模式遗漏点:re模块其实也是帮助我们进行字符串处理的重要工具,我之前总是想着用内建的函数来处理,其实如果是复杂的文本和数据结构,re模块能帮助我们处理很多信息。对

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

遗漏点: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 '
>>>

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网