python - 在 python 中以特定条件匹配字符串上的数字

标签 python

我有一个字符串序列的形式

s1 = "Schblaum 12324 tunguska 24 234n"
s2 = "jacarta 331 matchika 22 234k"
s3 = "3239 thingolee 80394 234k"

我需要将这些字符串分成两个字符串,就在字符串中间的数字之后,忽略字符串的第一部分是否有数字。有点像

["Schblaum 12324", "tunguska 24 234n"]
["jacarta 331", "matchika 22 234k"]
["3239 thingolee 80394", "bb 6238"]

我尝试在表单中使用正则表达式

finder = re.compile(""\D(\d+)\D"")
finder.search(s1)

没有用。有没有办法做到这一点,也许不使用正则表达式? 干杯!

编辑:刚刚发现初始字符串只是

"jacarta 43453"

没有其他部分。这应该返回

["jarcata 43453"]

最佳答案

使用re.findall

>>> import re
>>> s1 = "Schblaum 12324 tunguska 24 234n"
>>> re.findall(r'^\S+\D*\d+|\S.*', s1)
['Schblaum 12324', 'tunguska 24 234n']
>>> s2 = "jacarta 331 matchika 22 234k"
>>> s3 = "3239 thingolee 80394 234k"
>>> re.findall(r'^\S+\D*\d+|\S.*', s2)
['jacarta 331', 'matchika 22 234k']
>>> re.findall(r'^\S+\D*\d+|\S.*', s3)
['3239 thingolee 80394', '234k']

关于python - 在 python 中以特定条件匹配字符串上的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33527013/

相关文章:

python - 如何在 Python 中为抽象类定义构造函数实现?

python - Python 中的条件嵌套循环

python - Django Admin - 适用于一个整数模型的选择,但不适用于另一个

python - 为什么我不能用单列矩阵替换 NumPy 数组中的列?

python - PLY 可以处理输入而不将其全部加载到内存中吗?

python - 索引错误 : Layer [4] not found

python - [WebSphere] : Items are not properly appending to a list and regex is failing

python - 在 Python 中复制迭代器

python - "import tensorflow as tf"导入错误 : Could not find 'cudart64_90.dll'

python - 在读取 Python 文件中的行时跳过前几行