去掉字符串中的符号和空格

xiaoxiao2021-02-28  82

去掉符号:

1、使用str.translate:

>>> from string import punctuation >>> lis = ["hel?llo","intro"] >>> [ x.translate(None, punctuation) for x in lis] ['helllo', 'intro'] >>> strs = "5,6!7,8" >>> strs.translate(None, punctuation) '5678'

2、使用正则表达式:

>>> import re >>> [ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis] ['helllo', 'intro'] >>> re.sub(r'[{}]+'.format(punctuation),'', strs) '5678'

3、使用list的comprehension和str.join:

>>> ["".join([c for c in x if c not in punctuation]) for x in lis] ['helllo', 'intro'] >>> "".join([c for c in strs if c not in punctuation]) '5678'

去掉空格

>>> a = ' ddd dfe dfd efre ddd ' >>> a.strip() # 去掉两边的空格 'ddd dfe dfd efre ddd' >>> a.lstrip() # 去掉左边的空格 'ddd dfe dfd efre ddd ' >>> a.rstrip() # 去掉右边的空格 ' ddd dfe dfd efre ddd' >>> a.replace(' ', '') 'ddddfedfdefreddd' >>> a.split() ['ddd', 'dfe', 'dfd', 'efre', 'ddd']
转载请注明原文地址: https://www.6miu.com/read-28229.html

最新回复(0)