【发布时间】:2019-03-14 16:30:25
【问题描述】:
def strip_string(s):
import re
replaced_string = re.sub('[^\\w/]+', '_', s)
return replaced_string
print(strip_string('h^&ell`., |o w/p]{+p__orld'))
【问题讨论】:
标签: regex python-3.x replace
def strip_string(s):
import re
replaced_string = re.sub('[^\\w/]+', '_', s)
return replaced_string
print(strip_string('h^&ell`., |o w/p]{+p__orld'))
【问题讨论】:
标签: regex python-3.x replace
如果您想使用regex 将字符串中的多个_ 替换为单个_,您可以这样做
replaced_string = re.sub('[_]+', '_', s)
完整代码,
import re
def strip_string(s):
replaced_string = re.sub('[_]+', '_', s)
return replaced_string
print(strip_string('h^&ell`., |o w/p]{+p__orld'))
print(strip_string('hello___world__'))
# Output
h^&ell`., |o w/p]{+p_orld
hello_world_
【讨论】: