Python如何仅在值post selected delimiter为数字时分割字符串?

Python如何仅在值post selected delimiter为数字时分割字符串?,python,split,Python,Split,我正在尝试使用lib-re拆分字符串,需要使用一些分隔符拆分值,但是对于一个特定的字符串,我遇到了一些小问题。问题是,如果空格后面的下一个字符是数字,我就需要拆分。 比如说 import re a = 'Trying de one' b = 'Trying de 10' a = re.split('ate |de |do ',a)[0] b = re.split('ate |de |do ',b)[0] 我需要的是输出: a = 'Trying de one' b = 'Trying de '

我正在尝试使用lib-re拆分字符串,需要使用一些分隔符拆分值,但是对于一个特定的字符串,我遇到了一些小问题。问题是,如果空格后面的下一个字符是数字,我就需要拆分。 比如说

import re
a = 'Trying de one'
b = 'Trying de 10'
a = re.split('ate |de |do ',a)[0]
b = re.split('ate |de |do ',b)[0]
我需要的是输出:

a = 'Trying de one'
b = 'Trying de '

每次我都会得到第二个。

您可以捕获
ate
de或
do
后跟一个要保留的空格,然后匹配一个或多个要删除的数字

在替换中,使用捕获组1

import re

pattern = r"\b(ate |d[eo] )\d+";

a = 'Trying de one'
b = 'Trying de 10'

a = re.sub(pattern, r'\1', a)
b = re.sub(pattern, r'\1', b)

print(a)
print(b)
|

输出

Trying de one
Trying de 
Trying de one
Trying de 

如果必须使用split,一个选项是使用lookarounds,在左侧断言
ate
do
,在右侧断言一个数字

import re

pattern = r"(?:(?<=ate )|(?<=d[eo] ))(?=\d)"

a = 'Trying de one'
b = 'Trying de 10'

a = re.split(pattern, a)
b = re.split(pattern, b)
print(a[0])
print(b[0])

|

您想要拆分还是替换?