如何使用Python re.sub删除字符串后的所有内容

如何使用Python re.sub删除字符串后的所有内容,python,regex,Python,Regex,如果我有这样的句子: To contact me, please dial in the number: 300801 我想删除“拨号”后的所有内容以保留: To contact me, please dial 如何使用re.sub完成此操作?完整解释器会话: >>> s = "To contact me, please dial in the number: 300801" >>> import re >>> re.sub("dial

如果我有这样的句子:

To contact me, please dial in the number: 300801
我想删除“拨号”后的所有内容以保留:

To contact me, please dial

如何使用re.sub完成此操作?

完整解释器会话:

>>> s = "To contact me, please dial in the number: 300801"
>>> import re
>>> re.sub("dial .*", "dial", s)
'To contact me, please dial'

不过,使用标准的字符串切片和
string.find()
(如您问题的注释所示)可能会更容易。

string.split('dial')[0]+'dial'
打印(s[:s.find('dial')+4])
?您只需要这句话吗?可能有一些更一般的规则,我们不知道know@KevinLing请标记一个答案以结束问题(如果有帮助的话)!