2024-05-11 03:28:38 发布
网友
我是一个同时使用Python和RegEx的初学者,我想知道如何创建一个字符串,它接受符号并用空格替换它们。任何帮助都很好。
例如:
how much for the maple syrup? $20.99? That's ricidulous!!!
进入:
how much for the maple syrup 20 99 That s ridiculous
有时计算regex比用python编写要花更长的时间:
import string s = "how much for the maple syrup? $20.99? That's ricidulous!!!" for char in string.punctuation: s = s.replace(char, ' ')
如果需要其他字符,可以将其更改为使用白名单或扩展黑名单。
白名单示例:
whitelist = string.letters + string.digits + ' ' new_s = '' for char in s: if char in whitelist: new_s += char else: new_s += ' '
使用生成器表达式的白名单示例:
whitelist = string.letters + string.digits + ' ' new_s = ''.join(c for c in s if c in whitelist)
我经常打开控制台,在objects方法中寻找解决方案。它经常已经在那里了:
>>> a = "hello ' s" >>> dir(a) [ (....) 'partition', 'replace' (....)] >>> a.replace("'", " ") 'hello s'
简而言之:使用string.replace()。
string.replace()
单向,使用regular expressions:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!" >>> re.sub(r'[^\w]', ' ', s) 'how much for the maple syrup 20 99 That s ridiculous '
\w将匹配字母数字字符和下划线
\w
[^\w]将匹配任何而不是字母数字或下划线的内容
[^\w]
有时计算regex比用python编写要花更长的时间:
如果需要其他字符,可以将其更改为使用白名单或扩展黑名单。
白名单示例:
使用生成器表达式的白名单示例:
我经常打开控制台,在objects方法中寻找解决方案。它经常已经在那里了:
简而言之:使用
string.replace()
。单向,使用regular expressions:
\w
将匹配字母数字字符和下划线[^\w]
将匹配任何而不是字母数字或下划线的内容相关问题 更多 >
编程相关推荐