python技巧类似Excel中Trim字符串的方法你知道多少?

在python中,删除字符串中的空格、空行,tab制表符、行结束符等特殊字符的方法多种多样,比较灵活。常见的用法有删除字符串开始或末尾的空格,但也可以删除字符串中间的空格、还可以删除tab制表符、回车符等操作。删除不需要的字符,便于比较字符串。众所周知,excel中使用trim函数删除字符串首尾部的空格,但python中的字符串格式提供了lstrip()、rstrip()和strip()方法,实现类似trim的功能。

python的str 类型提供了一个删除字符串开头的字符串的函数:str.lstrip,调用这个函数不需要参数,就可以把字符串的开头的空格删除。

>>>'   hello   '.lstrip()
'hello   '

但是如果只想删除开头的第一个空格,可以对该字符串进行切分,代码如下:

>>> s = '   hello'
>>> s = s[1:]
>>> s
'  hello'

对于不能确定目标字符串的开头是否有1个以上的空格,就需要先检查:

>> def strip_first(s: str, ch: str = ' ') -> str:
     if s and s[0] == ch:
         return s[1:]
     return s

>>> strip_first('hello')
'hello'

>>> strip_first('   hello')
 '  hello'

删除字符串尾部的空格

python的str 类型提供了 专门的函数:str.rstrip,这个函数可以指定要删除的字符串尾部的字符,如不指定字符,则默认为删除字符串尾部的空格,代码如下:

>>> '   hello   '.rstrip()
'   hello'
>>> '***hello***'.rstrip('*')
'***hello'

如果要求只删除字符串尾部的最后一个空格或字符,可以采用与上文所说的类似的方法,先要检查字符串尾部是否有1个以上的空格,代码如下:

>>> def strip_last(s: str, ch: str = ' ') -> str:
     if s and s[-1] == ch:
         return s[:-1]
     return s


>>> strip_last('hello')
'hello'

>>> strip_last('hello ')
'hello'

>>> strip_last('')
''

删除字符串中所有的空格或指定的字符

可以用 str.strip 函数删除指定字符串中所有的空格或指定的字符,不仅包括开头或末尾的空格,也包括字符串中间的空格。strip()函数不指定参数,则默认为空格;strip(‘*’),则删除字符串中的 ‘*’ ,代码如下:

>>> '   hello   '.strip()
'hello'

>>> '***hello***'.strip('*')
'hello'

删除空行

可以利用 strip() 函数可以指定要删除的字符这一特点,指定要删除的字符为 “\n” ,即可删除一段字符串文字中的空行,操作如下:

>>> s = """
... 
... 
...  hello
... 
... 
... """
>>> s
'\n\n\n hello\n\n\n'
>>> s.strip('\n')
' hello'

删除回车符

用strip函数删除字符串中的软回车符(’\r’)或硬回车符(’\n’), 两者连接在一起 ‘\r\n’ 就形成新的一行,删除这样的行,就要删除回车符,操作如下:

>>> s = "  hello world\r\n\r\n"
>>> print(s)
  hello world


>>> s.strip('\r\n')
'  hello world'

删除制表符tab

python中删除字符串中的制表符tab,使用str.strip(‘\t’)即可,操作如下:

>>> s = "\t\t\t  hello  world \t"       
>>> s
'\t\t\t  hello  world \t'
>>> print(s)
              hello  world     
>>> s.strip('\t')
'  hello  world '

删除字符串中某种字符组合

上文中,好几处地方都在使用str.strip()函数时指定了参数,该参数可以是单个的字符,也可以是多个字符,利用这一点,就可以使用该函数删除指定字符串中的某些字符串组合,示例如下:

>>> s = "  \ns hello world \n    s"
>>> s    
'  \ns hello world \n    s'
>>> print(s)

s hello world 
    s
>>> s.strip('\n s')
'hello world'

删除字符串中多个空格

有时候需要删除一句或一段文字中多余或重复的空格,单词之间只保留一个空格,这样文字就比较规范,示例如下:

>>> import re
>>> s = "   Python   is really   a    great language.    "
>>> re.sub("\s+" , " ", s)
' Python is really a great language. '

以上方法使用正则函数re.sub(), 把连续空格超过3个以上的片段字符,只保留1个空格。

还可以用split()函数先把字符串切分,再用join()函数连接,示例如下:

>>> s = "   Python   is really   a    great language.    "
>>> " ".join(s.split())
'Python is really a great language.'
>>> # This is the same as using regex then stripping the whitespaces
>>> re.sub("\s+" , " ", s).strip()
'Python is really a great language.'

删除字符串列表的元素中的空格或特殊字符

与删除一个字符串中的空格或特殊字符的方法一样,只需要做迭代操作,示例如下:

>>> lst = ["string1\n", "string2\n", "string3\n"]
>>> [s.strip('\n') for s in lst]
['string1', 'string2', 'string3']

删除字符串数组的元素中的空格或特殊字符

Numpy工具包中不仅有.lstrip, .rstrip, .replace这样的字符串操作函数,而且还有更多的其他字符串操作函数,但是这与python内置的方法还是有点差别,numpy中使用nump.char函数模块,因此其参数必须是向量化的数组或字符的列表。用法示例如下:

>>> import numpy as np
>>> arr = np.array([' helloworld   ', ' hello'])
array([' helloworld   ', ' hello'], dtype='<U7')
>>> np.char.strip(arr, ' ')
array(['helloworld', 'hello'], dtype='<U7')

(本文完)

python技巧类似Excel中Trim字符串的方法你知道多少?

发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/76335
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!

(0)
股市刺客的头像股市刺客
上一篇 2024 年 7 月 12 日
下一篇 2024 年 7 月 12 日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注