【发布时间】:2022-01-28 17:34:52
【问题描述】:
示例。我有这句话:“Hello__my_beautiful___friends!” 我想要这个:“Hello_my_beautiful_friends!” 我怎样才能做到这一点?如何删除字符串中的2个或多个符号“_”?
【问题讨论】:
示例。我有这句话:“Hello__my_beautiful___friends!” 我想要这个:“Hello_my_beautiful_friends!” 我怎样才能做到这一点?如何删除字符串中的2个或多个符号“_”?
【问题讨论】:
你可以使用re.sub:
In [5]: re.sub('_+', '_', s)
Out[5]: 'Hello_my_beautiful_friends!'
这使用re.sub(patter, replacement, string),其中_+ 表示一个或多个_,并将其替换为一个下划线。
【讨论】:
这样
my_string = "Hello__my_beautiful___friends!"
while "__" in my_string:
my_string = my_string.replace("__","_")
请注意,循环是必需的,因为您可能需要删除连续的“__”,并且需要多次迭代
【讨论】:
replace 将进行多次替换。它需要一个可选的第三个参数来限制替换的数量。