使用正则表达式Python在数字旁边找到字母时拆分字符串

时间:2016-07-25 18:16:08

标签: python regex

我有一个像这样的字符串

string = "3,197Working age population"

我希望打破字符串,以便当数字3,197结束并且工作年龄人口开始使用正则表达式或任何其他有效方法时。总之,我只需要3,197

1 个答案:

答案 0 :(得分:0)

您可以查看itertools.takewhile

from itertools import takewhile

string = "3,197Working age population"
r = ''.join(takewhile(lambda x: not x.isalpha(), string))
print(r)
# '3,197'

字符串中取项,而尚未到达字母。使用join

将结果重新转换为字符串