如何使用regex删除所有符号,但将blank替换为“”

2024-07-04 07:54:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道正则表达式就是这样

re.sub(r'[^\w]', '', string)

我可以从字符串中删除符号。但我现在想要的是删除所有其他符号,但将空格替换为“-”。有什么办法吗?你知道吗

例如

string = "Felix's 3D's"
# I want it as "Felixs-3D"

谢谢!你知道吗


Tags: 字符串restringas符号it空格want
3条回答

如果要用-替换空格,则忽略并结构更换地址:

print(re.sub(r'[^\w\s]', '',string).replace(" ","-"))
Felixs-3Ds

像这样:

>>> st= "Felix's 3D's"
>>> re.sub(r'(\s)|[^a-zA-Z]', lambda m: '-' if m.group(0).isspace() else '', st)
'Felixs-Ds'

您也可以在不使用正则表达式的情况下执行此操作:

>>> st.translate(None,"'").replace(' ','-')
'Felixs-3Ds'

您可以将所有目标“特殊”字符放在第二个参数中进行翻译。你知道吗

您可以指定一个函数来执行以下操作:

def replace(match):
    return '-' if match.group().isspace() else ''

re.sub(r'[^\w]', replace, string)

演示:

>>> import re
>>> def replace(match):
...     return '-' if match.group().isspace() else ''
... 
>>> string = "Felix's 3D's"
>>> re.sub(r'[^\w]', replace, string)
'Felixs-3Ds'

docs

re.sub(pattern, repl, string, count=0, flags=0)

...

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

因此,replace将接收每个匹配,并返回'-'(如果它是空格),否则返回''。你知道吗

相关问题 更多 >

    热门问题